2013-04-01 52 views
1

我在我的页面上有一个语言选择器选项的下拉菜单。在选择语言时,我希望我的标签和按钮html可以根据语言进行更改? 我的代码在更改语言时更改div的所有元素(html)?

var arr = []; 
    // gets all the ids starting with comp_ 
    $('div[id^="comp_"]').each(function(){ 
     arr.push(this.id); 
     labels = $(this).find('label'); 
     buttons = $(this).find('button'); 

     //get all labels inside the current div 
     $(labels,buttons).each(function(){ 
      $(this).html(""); 
     }); 

    }); 
    console.log(arr); 
}, 

* 问题* 只reference.can我运行多个元素引用的函数改变标签元素的参考,而不是按钮?

它工作,如果我这样做,但我不想再重复相同的代码不同影响引用

var arr = []; 
    // gets all the ids starting with comp_ 
    $('div[id^="comp_"]').each(function(){ 
     arr.push(this.id); 
     labels = $(this).find('label'); 
     buttons = $(this).find('button'); 

     //get all labels inside the current div 
     $(labels).each(function(){ 
      $(this).html(""); 
     }); 

     $(buttons).each(function(){ 
      $(this).html(""); 
     }); 

    }); 
    console.log(arr); 
}, 

回答

2

是:

labels.add(buttons).each(function(){ 
     $(this).html(""); 
    }); 

或者只是:

labels.add(buttons).html(''); 

缩短一个字符:

labels.add(buttons).empty(); 

.add() jQuery方法用于将元素添加到现有的jQuery集合中。这些示例使用.add()来组合“标签”和“按钮”jQuery对象中的元素。如果你对每个元素都做了不变的事情,那么后面两个是表明你不需要.each()。大多数jQuery函数都在集合的每个元素上运行。

完全不同的方式来简化:

var labelsAndButtons = $(this).find('label, button'); 
    labelsAndButtons.empty(); 

在选择字符串,是喜欢 “或”。该示例查找标签名称为“标签”“按钮”的所有元素。

+0

对......如果你能解释上面的代码是干什么的?它的作品只是想知道如何因为我可能需要添加更多的元素引用..感谢 – inputError

+0

在编辑 – inputError

+1

@ user2125700后得到它好吧我添加了一些更多的细节。 – Pointy