我对 javascript/jquery 很陌生,想知道是否有可能收集 div 的类名,然后使用 jQuery 根据这些类名创建复选框。例如。
<div class="champ">
<h3>Reading</h3>
</div>
<div class="league1">
<h3>Sheffield Wednesday</h3>
</div>
<div class="prem">
<h3>Sunderland</h3>
</div>
<div class="prem">
<h3>Tottenham Hotspur</h3>
</div>
<div class="champ">
<h3>Watford</h3>
</div>
假设这是我的带有关联类名的 html 文件,我本质上希望结果能够吐出带有 div 中存在的类名的复选框,同时避免相同类名的任何重复。
所以对于上面的例子,它最终看起来像
- 冠军
- 联赛1
- prem
感谢任何帮助。
最佳答案
我个人建议:
// creating new elements:
var newCheckbox = $('<input />', {
'type' : 'checkbox',
'name' : 'UKFootballClubs'
}),
newLabel = $('<label />');
wrapper = $('<div />').appendTo('body');
// iterating over each div that has a class:
$('div[class]').each(function(){
/* appending a cloned label element, with the text set to the class-name
of the current div element: */
newLabel.clone().text(this.className).appendTo(wrapper);
/* appending a clone of the new checkbox to the new label,
this allows a click on the label to un/select the checkbox: */
newCheckbox.clone().prependTo(wrapper.find('label').last());
});
稍作修改的版本,使用团队名称(来自 div
)作为标签
文本,以避免出现两个带有 的复选框>prem
文本:
var newCheckbox = $('<input />', {
'type' : 'checkbox',
'name' : 'UKFootballClubs'
}),
newLabel = $('<label />');
wrapper = $('<div />').appendTo('body');
$('div[class]').each(function(){
newLabel.clone().text($(this).text()).appendTo(wrapper);
newCheckbox.clone().prependTo(wrapper.find('label').last());
});
但是,如果您更愿意使用类名称(“prem”、“champ”等),那么您可以通过在附加新元素之前检查包含该文本的元素是否存在来防止重复的复选框文本与该文本:
var newCheckbox = $('<input />', {
'type' : 'checkbox',
'name' : 'UKFootballClubs'
}),
newLabel = $('<label />');
wrapper = $('<div />').appendTo('body');
$('div[class]').each(function(){
var text = $.trim(this.className);
if (!wrapper.find('label:contains('+text+')').length) {
newLabel.clone().text(text).appendTo(wrapper);
newCheckbox.clone().prependTo(wrapper.find('label').last());
}
});
引用文献:
-
appendTo()
. -
:contains()
selector . -
clone()
. -
each()
. -
find()
. -
last()
. -
prependTo()
. -
text()
.
关于javascript - jQuery 扫描 div 类名,使用这些类名打印匹配的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18485911/