如何删除特定按钮,例如我有
<div>
<button>1</button>
<button>2</button>
<button>3</button>
</div>
然后我想删除jquery中的特定按钮,我尝试使用这样的删除功能
$('button').remove(2)
但它不起作用,您知道解决此问题的其他选项吗?
最佳答案
.remove()接受可选的选择器,而不是索引。
如果您尝试删除第三个按钮(索引 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>
或者对于多个连续索引,使用 .slice()
$("button").slice(0, 2).remove() // remove the first two
如果您尝试删除文本内容为“2”的按钮,可以使用 :contains() selector或使用更准确的.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>
关于javascript - 如何删除jquery中的特定按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69671711/