Streamlining my javascript with a function

自闭症网瘾萝莉.ら 提交于 2019-12-13 02:24:40

问题


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.

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.

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?

here is the clunky code

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}); ;
     });

});

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...


回答1:


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
        });
    });
}



回答2:


Something like this might help:

 function bindSelectFeature(select, featured) {
    $(select).addEvent('change', function(e){
        pidselected = this.options[this.selectedIndex].getProperty('value') ;
        $(featured).setProperties({
          value: pidselected
        });
     });
  });
  bindSelectFeature('recipesproductpasta','featuredproductidpasta');


来源:https://stackoverflow.com/questions/2775630/streamlining-my-javascript-with-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!