Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery元素是否有ID?_Javascript_Jquery - Fatal编程技术网

Javascript jQuery元素是否有ID?

Javascript jQuery元素是否有ID?,javascript,jquery,Javascript,Jquery,如何选择具有任何ID的元素?例如: if ($(".parent a").hasId()) { /* then do something here */ } 一、 我绝对不是jQuery的主控程序。具有id属性的.a父元素的数量: $('.parent a[id]').length 像这样: var $aWithId = $('.parent a[id]'); 根据OP的评论,按如下方式进行测试: if($aWithId.length) //or without using var

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

if ($(".parent a").hasId()) {
    /* then do something here */
}
一、 我绝对不是jQuery的主控程序。

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

$('.parent a[id]').length
像这样:

var $aWithId = $('.parent a[id]');
根据OP的评论,按如下方式进行测试:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
将返回具有类父元素的元素中的所有锚定标记,这些元素具有指定的属性ID

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

您可以使用以下代码:

   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;
       }
   });
同样的问题也可以在这里找到:

只需使用:

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

您可以使用jQuery的.is函数

如果$.parent a.isidSelector{

//Do stuff
}

如果父锚点具有idSelector id,则返回true。

纯js方法:

var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
简单方法:

这是你的html

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

您可以使用每个函数计算所有a标记,并将单击绑定到您单击的特定元素。然后用if语句抛出一些逻辑


我似乎能够用以下方法解决这个问题:

if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}
您可以这样做:

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

    /* then do something here */

}

Use.is“[id]”;检查特定元素是否具有id属性。或者,如果需要筛选元素集合,请使用.filter“[id]”,然后比较.length属性。为什么要这样做?您实际计划做什么?可能与jQuery文档重复:。是否要选择要对其执行操作的元素,或测试是否存在任何此类元素?您的意思是如果$'.parent a[id]'.length?但问题是元素为复数,and.attr将只从与该选择器匹配的第一个元素中获取id。您是对的,因此它的长度大于$'.parent a[id]'.length。答案已更新否,OP正在尝试确定哪些元素的id属性定义为任何值,而不是通过特定的已知id进行选择。但问题是元素为复数,并且.attr将仅从与该选择器匹配的第一个元素获取id。OP已提供了完全相同的答案:。否。这将告诉您某个元素是否具有特定id。问题是询问它是否具有任何id。请参阅两年前接受的答案。如果您想检查该元素是否具有特定id,这是一个很好的答案+1欢迎使用堆栈溢出!这个答案已经提供了多次。请先核对其他答案。
if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}
if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}