繁体   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