2013-04-01 53 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