当jQuery选择器保存在变量if元素中时删除如何知道删除

时间:2016-09-07 20:20:26

标签: javascript jquery

在类似的问题中,据说如果不是0则获取长度属性意味着存在。

但是在过去你选择元素并在删除元素后保存在变量中,如果得到长度则会看到长度不是0 !!!!

在jQuery 1.10.2中测试它

var x = $("h3:first")
$("h3:first").remove();
x.length

2 个答案:

答案 0 :(得分:1)

您可以检查父母。

var $x = $("h3:first");

console.log($x.parent().length);

$x.remove();

console.log($x.parent().length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h3>Here I am</h3>

答案 1 :(得分:0)

下面是一个示例,如果您只有一个h3,那么x保持长度,但重新运行查询会返回0,因为它不再存在。

&#13;
&#13;
var x = $("h3:first");
$("h3:first").remove();
console.log(x.length);
console.log($("h3:first").length);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h3>Here I am</h3>
&#13;
&#13;
&#13;