Javascript 如何使用jQuery循环遍历以特定字符串开头的每个div?
我试图循环遍历以单词“hold”开头的每个div,如果它不存在于另一个对象中,则选中remove 这就是我所做的Javascript 如何使用jQuery循环遍历以特定字符串开头的每个div?,javascript,jquery,Javascript,Jquery,我试图循环遍历以单词“hold”开头的每个div,如果它不存在于另一个对象中,则选中remove 这就是我所做的 $.each($("div[id^='Held']"), function(key, val){ var divName = $(this).attr('id'); var uniqueId = divName.replace('Held', ''); if ($.inArray(uniqueId, data.onHold) === -1){
$.each($("div[id^='Held']"), function(key, val){
var divName = $(this).attr('id');
var uniqueId = divName.replace('Held', '');
if ($.inArray(uniqueId, data.onHold) === -1){
$('#' + ivName).remove();
}
});
我也尝试过这种语法
$("div[id^='Held']").each(function(key, val){
var divName = $(this).attr('id');
var uniqueId = divName.replace('Held', '');
if ($.inArray(uniqueId, data.onHold) === -1){
$('#' + ivName).remove();
}
});
但是它没有按预期删除div我会使用
键
参数:
var elms = $("div[id^='Held']");
elms.each(function(key, val){
var divName = $(this).attr('id');
var uniqueId = divName.replace('Held', '');
if ($.inArray(uniqueId, data.onHold) === -1){
elms.eq(key).remove();
}
});
如果变量中已经有要删除的元素,则无需使用选择器
$("div[id^='Held']").each(function(){
var divName = this.id;
var uniqueId = divName.replace('Held', '');
if ($.inArray(uniqueId, data.onHold) === -1){
$(this).remove();
}
});
您还可以使用.filter
:
$("div[id^='Held']").filter(function() {
var uniqueId = this.id.replace('Held', '');
return $.inArray(uniqueId, data.onHold) === -1;
}).remove();
问题是在数组中搜索项时。我的数组的每个值中都有一个对象 下面是我为纠正这个问题所做的工作
//This will search for all div with Id starts with "Held" and it will loop through them
$("div[id^='Held']").each(function(){
var divName = this.id;
var uniqueId = divName.replace('Held', '');
if ( isItemExists(uniqueId, data.onHold, 'interactionId') ){
this.remove();
}
});
// This function will find a value inside a
function isItemExists(needle, haystack, elementKey){
return $.grep(haystack, function(item){
return item.elementKey== needle;
});
};
键入的
ivName
是真代码还是复制错误?为什么不直接使用$(this).remove()
?可以使用参数“key”,您应该使用第二种语法<代码>$。每个用于数组和对象,$(选择器)。每个()
用于jQuery集合。请检查以下内容: