Javascript 如何检查div是否有id?
我正在尝试从循环中获取id。如果没有Javascript 如何检查div是否有id?,javascript,jquery,Javascript,Jquery,我正在尝试从循环中获取id。如果没有id属性attr方法将返回未定义的。只要写下: Uncaught Type Error: Cannot read property 'length' of undefined 如果要多次使用$(this),建议查找一次,并将结果jQuery对象放入局部变量中。demo APi链接: 请试试这个,这个应该有用 代码 var $this = $(this); if (typeof $this.attr("id") != "undefined" &&
id
属性attr
方法将返回未定义的。只要写下:
Uncaught Type Error: Cannot read property 'length' of undefined
如果要多次使用$(this)
,建议查找一次,并将结果jQuery对象放入局部变量中。demo
APi链接:
请试试这个,这个应该有用
代码
var $this = $(this);
if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) {
...
}
if(this.id)
是您所需要的全部
为什么这会起作用?
如果元素具有ID,则该值将是一个非空字符串,其计算结果总是true
如果没有ID,则该值为空字符串,其计算结果为false
我正在尝试从循环中获取ID
要获取ID列表,可以使用.map
如下所示:
$(".ui-droppable").each(function () {
if($(this).prop("id").length > 0)
{
alert('here');
}
});
或者使用选择器。使用属性选择器选择器[属性]
仅获取具有ID的元素
var ids = $(".ui-droppable").map(function() {
return this.id ? this.id : null;
}).get();
就你而言:
$('.myClass[id]') // Get .myClass elements that have ID attribute
我希望这听起来不太粗鲁,但我认为在你开始使用jquery之前,你应该了解更多关于JavaScript的知识jquery是一个奇怪的悖论。它的设置使JavaScript编程变得简单,这对初学者来说非常好;但是,它仍然是JS,因此用户首先应该至少熟悉本机JavaScript对象交互(属性/方法调用)描述性替代方法:if(this.id&&this.id.length>$somenum)
这也是一个很好的答案,它了解了问题的目的,但不一定是问问题
var ids = $(".ui-droppable").map(function() {
return this.id ? this.id : null;
}).get();
$('.myClass[id]') // Get .myClass elements that have ID attribute
$('.ui-droppable[id]').each(function(){
alert( this.id );
});
if(typeof $(this).attr("id") != 'undefined')