[英]jquery remove/ select element from class by index
I want to remove some elements with class by the index. 我想通过索引删除一些带有类的元素。 Let me introduce. 我来介绍一下。
First, I create some divs, giving them class and an element after getting result from ajax. 首先,我创建了一些div,在从ajax获取结果后给它们提供类和元素。
$.ajax({
type: "POST",
url: "myphp.php",
data: {label: label},
success: function(result) {
var data ="";
for (i = 0; i<result.item.length; i++){
var data = result.item[i].data;
var div = $("<div class ='item'></div>");
var divData= "<p class ='divData' > "+ divData+"</p>";
}
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
Then, I want to remove all unnecessary divs with class = "detail" by clicking the necessary one. 然后,我想通过单击必要的删除所有不必要的div与class =“detail”。
$( document ).on( 'click', '.detail', function() {
var numItems = $('.detail').length;
for ( i = 0; i<= numItems; i++) {
if ( i != $(this).index()){ // if the div is not selected
$(".detail").remove(i);//remove unnecessary div
}
}
});
I do not know how to remove one element with class ="detail" by index , why $(".detail").remove(i);
我不知道如何用index删除一个带有class =“detail”的元素,为什么$(".detail").remove(i);
can not be used? 不能使用? It is logical, isn't it? 这是合乎逻辑的,不是吗?
Try to use .not()
filter at this context to ease your job, 尝试在此上下文中使用.not()
过滤器来简化您的工作,
$(document).on( 'click', '.detail', function() {
$(".detail").not(this).remove();
});
There is no need to iterate over all the elements. 无需迭代所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.