Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果出现两次,jquery将删除元素_Javascript_Jquery_Html - Fatal编程技术网

Javascript 如果出现两次,jquery将删除元素

Javascript 如果出现两次,jquery将删除元素,javascript,jquery,html,Javascript,Jquery,Html,我的html中有如下内容: <div class="onlyContent"> <!-- some more stuff here --> </div> <div class="onlyContent"> <!-- some more stuff here --> </div> 我发现您可以使用第n个子选择器,但尝试以这种方式访问它并不适合我 $('.onlyContent:nth-child(2)').r

我的html中有如下内容:

<div class="onlyContent">
    <!-- some more stuff here -->
</div>
<div class="onlyContent">
    <!-- some more stuff here -->
</div>
我发现您可以使用第n个子选择器,但尝试以这种方式访问它并不适合我

$('.onlyContent:nth-child(2)').remove(); 
您可以使用
:eq(1)
以匹配集中的第二个元素为目标:

$('.onlyContent:eq(1)').remove(); 
如果元素数超过两个,则应使用
:not(:first)
:gt(0)


使用下面的代码。使用jQuery选择器

选择匹配集中索引n处的元素

检查

你可以试试这个-

   $('.onlyContent:gt(0)').remove();

它将删除所有重复项。只有第一个将出现。

您可以使用
.slice
进行此操作

$(".onlyContent").slice(1).remove();
又好又简单,没什么大不了的

.slice
文档中:

将匹配元素集减少到一个由 指数


您可以找到更多信息。

使用.length属性检查页面上选定元素的数量,如果其值大于1,则删除除first之外的元素

if($('.onlyContent').length > 1) {
$('.onlyContent:gt(0)').remove();
}
你可以试试

$(".onlyContent").not(':first').remove();
你可以试试这个

$('.onlyContent:gt(0)').remove();

当jquery方法能够自行处理时,检查非常困难。@A.Wolff answer updated。我认为它给出了
未定义的
如果没有可用的元素,那么您的代码正在工作,检查非常简单superflu@A.Wolff正确的。这是没有必要的。谢谢
$(".onlyContent").slice(1).remove();
if($('.onlyContent').length > 1) {
$('.onlyContent:gt(0)').remove();
}
$(".onlyContent").not(':first').remove();
$('.onlyContent:gt(0)').remove();