[英]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'));
只需使用:
$(".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.