![](/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.