![](/img/trans.png)
[英]In jQuery, what's the proper way to “move” an element from its parent to another element?
[英]What's the proper way to check if an element has an ID or not with jQuery?
我以为我可以检查一个元素是否有一个带有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>
尝试下面应该工作的东西:
<div id=""></div>
$(document).ready(function(){
if($('div').attr('id') != ''){
alert("have id");
}else{
alert("do not have id")
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.