繁体   English   中英

jQuery如果Element有ID?

[英]jQuery if Element has an ID?

如何选择具有任何ID的元素? 例如:

if ($(".parent a").hasId()) {
    /* then do something here */
}

我绝不是jQuery的高手。

像这样:

var $aWithId = $('.parent a[id]');

根据OP的评论,测试如下:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)

将返回具有指定属性ID的类parent的元素内的所有锚标记

您可以使用jQuery的.is()函数。

if($(“。parent a”)。is(“#idSelector”)){

 //Do stuff 

}

如果父锚具有#idSelector id,它将返回true。

.parent a具有id属性.parent a元素的数量:

$('.parent a[id]').length

你可以做

document.getElementById(id) or 
$(id).length > 0

简单方法:

Fox示例这是你的html,

<div class='classname' id='your_id_name'>
</div>

Jquery代码:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}

您可以使用以下代码:

   if($(".parent a").attr('id')){

      //do something
   }


   $(".parent a").each(function(i,e){
       if($(e).attr('id')){
          //do something and check
          //if you want to break the each
          //return false;
       }
   });

同样的问题是你可以在这里找到: 如何检查div是否有id?

纯粹的js方法:

var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));

JsFiddle演示

只需使用:

$(".parent a[id]");

您可以使用each()函数来评估所有标记,并将click单击绑定到您单击的特定元素。 然后用if语句抛出一些逻辑。

请看这里的小提琴

$('a').each(function() {
    $(this).click(function() {
        var el= $(this).attr('id');
        if (el === 'notme') {
            // do nothing or something else
        } else {
            $('p').toggle();
        }
    });
});

我似乎已经能够解决它:

if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}

你可以这样做:

if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM