gpt4 book ai didi

javascript - 使用 jQuery 检查元素是否有 ID 的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 02:10:19 25 4
gpt4 key购买 nike

我想我可以用 has() 检查一个元素是否有 ID,如下所示:

if ($button.has('#Menu-Icon')[0] !== undefined) {
//do stuff
}

但我了解到,它会检查是否有与 ID 匹配的后代。所以我认为这不是正确的 jQuery 方法,但尽管如此,当我在 Google 上搜索该主题时,它似乎是唯一出现的东西。

哪种 jQuery 方法适合检查给定元素是否具有特定 ID?

最佳答案

使用 attr() 函数检查 id,如下所示:

$('button').on('click', function() {
if ($(this).attr('id') == 'TheID') {
alert('The button you pressed has the id: "TheID"!');
} else {
alert('You pressed a button with another id..');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="TheID">TheID</button>
<button id="anotherID">anotherID</button>

关于javascript - 使用 jQuery 检查元素是否有 ID 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32472170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com