循环遍历类的所有元素,我看到下面的代码仅影响数组中的第一个元素,但控制台日志记录了其中的每个元素。
del = $('<img class="ui-hintAdmin-delete" src="/images/close.png"/>')
$('.ui-hint').each(function(){
console.log($(this));
if ($(this + ':has(.ui-hintAdmin-delete)').length == 0) {
$(this).append(del);
}
});
这些元素都是非常简单的 div,里面只有文本。它们都没有我在 if 语句中寻找的类的元素,请仔细检查。尝试更改语句(使用 has()
、使用 children()
等)。我想我在这里错过了一些非常简单的东西,哈哈。
会欣赏输入。
最佳答案
我认为你需要的是(如果del
应该是一个字符串,如果它是一个dom元素引用那么你需要在附加之前克隆它)
$('.ui-hint').not(':has(.ui-hintAdmin-delete)').append(function(){
//you need to clone del else the same dom reference will be moved around instead of adding new elements to each hint
return del.clone()
});
关于javascript - $.each 只影响第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19628551/