我的页面上有一个下拉菜单,其中包含语言选择器选项。在选择语言时,我希望我的标签和按钮 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);
},
*问题 * 它只更改标签元素引用而不更改按钮引用。我可以在多个元素引用上运行该函数吗?
如果我这样做会起作用,但我不想为不同的引用再次重复相同的代码
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);
},
最佳答案
是的:
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();
选择器字符串中的 ,
类似于“或”。该示例查找标签名称为“label”或“button”的所有元素。
关于javascript - 在更改语言时更改 div 的所有元素(html)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15745435/