使用功能简化我的JavaScript [英] Streamlining my javascript with a function

查看:59
本文介绍了使用功能简化我的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列选择列表,我用它们来填充带有ID​​的文本框. 因此您单击一个选择选项,另一个文本框将填充其ID.

i have a series of select lists, that i am using to populate text boxes with ids. so you click a select option and another text box is filled with its id.

只有一个选择/ID对可以正常工作,但是我有多个,唯一改变的是选择和输入的ID.实际上,只是结尾更改,所有输入均以featredproductid和选择所有id均以配方产品开头,然后均以类别结尾.

with just one select/id pair this works fine, but i have multiples, and the only thing that changes is the id of the select and input.. in fact just the ending changes, the inputs all start with featredproductid and the select ids all start with recipesproduct and then both end with the category.

我知道一遍又一遍地列出每个类别并不是这样做的方法.我认为我需要对类别进行分类 var cats = [橄榄油",谷物",面食"] 然后使用forEach函数?也许吗?

i know that listing this over and over for each category is not the way to do it. i think i need to make an array of the categories var cats = ['olive oil', "grains", "pasta"] and then use a forEach function? maybe?

这是笨拙的代码

window.addEvent('domready', function() {
    $('recipesproductoliveoil').addEvent('change', function(e){
       pidselected = this.options[this.selectedIndex].getProperty('value') ;
   $("featuredproductidoliveoil").setProperties({
       value: pidselected}); ;
    });
       $('recipesproductgrains').addEvent('change', function(e){
           pidselected = this.options[this.selectedIndex].getProperty('value') ;
       $("featuredproductidgrains").setProperties({
           value: pidselected}); ;
        });
      $('recipesproductpasta').addEvent('change', function(e){
          pidselected = this.options[this.selectedIndex].getProperty('value') ;
      $("featuredproductidpasta").setProperties({
          value: pidselected}); ;
       });
    $('recipesproductpantry').addEvent('change', function(e){
        pidselected = this.options[this.selectedIndex].getProperty('value') ;
    $("featuredproductidpantry").setProperties({
        value: pidselected}); ;
     });

});

请记住,这是mootools 1.1(抱歉,我无法更新). 我确信这是一种基本的东西,似乎让我的脑袋缠绕了一下.但是我很确定按照上面的方法做并不是很好...

keep in mind this is mootools 1.1 (no i cant update it sorry). i am sure this is kind of basic, something i seem to have wrapping my brain around. but i am quite sure doing it as above is not really good...

推荐答案

您已经关闭.这是您可以做到的方式:

You're close. This is how you could do it:

var cats = ['oliveoil', 'grains', 'pasta'];
for (i in cats) {
    addChangeFunction(cats[i]);
}

function addChangeFunction(name) {
    $('recipesproduct' + name).addEvent('change', function(e) {
        pidselected = this.options[this.selectedIndex].getProperty('value');
        $('featuredproductid' + name).setProperties({
            value: pidselected
        });
    });
}

这篇关于使用功能简化我的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆