簡體   English   中英

使用jQuery檢查元素是否具有ID的正確方法是什么?

[英]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> 

您可以檢查id屬性,如底層元素

if ($button[0].id == 'Menu-Icon') {
   //do stuff
}

或jQuery方式使用.is()

if ($button.is('#Menu-Icon')) {
   //do stuff
}

has()方法用於通過檢查是否包含與傳遞的選擇器匹配的元素來過濾一組元素,同時它返回一個jQuery對象,因此檢查undefined永遠不會為true

嘗試下面應該工作的東西:

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM