[英]how to remove specific buttons in jquery
how can I remove specific buttons for example i have我怎样才能删除特定的按钮,例如我有
<div>
<button>1</button>
<button>2</button>
<button>3</button>
</div>
then i want to delete specific buttons in jquery,i tried use remove function like this然后我想删除 jquery 中的特定按钮,我尝试使用这样的删除功能
$('button').remove(2)
but it is not working do you know other options to resolve this proplem?但它不起作用你知道解决这个问题的其他选择吗?
You can also use nth child selector您还可以使用第 n 个子选择器
$("button:nth-child(2)").remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script> <div> <button>1</button> <button>2</button> <button>3</button> </div>
.remove() accepts an optional selector , not an index. .remove()接受一个可选的selector ,而不是一个索引。
If you're trying to remove the 3rd button (index 2), try narrowing the selection using .eq()如果您尝试删除第三个按钮(索引 2),请尝试使用.eq()缩小选择范围
$("button").eq(2).remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js" integrity="sha512-6ORWJX/LrnSjBzwefdNUyLCMTIsGoNP6NftMy2UAm1JBm6PRZCO1d7OHBStWpVFZLO+RerTvqX/Z9mBFfCJZ4A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div> <button>1</button> <button>2</button> <button>3</button> </div>
or for multiple consecutive indexes, use .slice()或者对于多个连续索引,使用.slice()
$("button").slice(0, 2).remove() // remove the first two
If you're trying to remove the button with text content "2" , you can use the :contains() selector or use a more accurate .filter()如果您尝试删除文本内容为"2"的按钮,您可以使用:contains() 选择器或使用更准确的.filter()
// $("button").remove(":contains(2)") $("button").filter((index, el}) => el.textContent.trim() === "2").remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js" integrity="sha512-6ORWJX/LrnSjBzwefdNUyLCMTIsGoNP6NftMy2UAm1JBm6PRZCO1d7OHBStWpVFZLO+RerTvqX/Z9mBFfCJZ4A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div> <button>1</button> <button>2</button> <button>3</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.