这里给出了Html
<div class="navBulletsWrapper">
<div rel="0" class=""></div>
<div rel="1" class=""></div>
<div rel="2" class=""></div>
<div rel="3" class=""></div>
<div rel="4" class="active"></div>
<div rel="5" class=""></div>
<div rel="6" class=""></div>
<div rel="7" class=""></div>
</div>
我希望得到类活跃
的div的rel值尝试了
$('.navBulletsWrapper .active')[0].attr('rel')
但失败,因为div没有attr
答案 0 :(得分:4)
$('.navBulletsWrapper .active')[0]
将为您提供 DOM 对象,而不是jquery对象;因此,它不会附加任何jquery函数,如attr
。
$('.navBulletsWrapper .active').eq(0).attr('rel')
应该有用。
如果您一次只有一个.active
div,则不必使用eq(0)
$('.navBulletsWrapper .active').attr('rel')
答案 1 :(得分:2)
仅限javascript的方法如下:
var divs = document.getElementsByClassName("navBulletsWrapper")[0].getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
if(divs[i].className=="active"){
var rel = divs[i].attributes.rel.value;
alert(rel);
break;
}
}
使用您尝试过的方法继续jquery方法 http://jsfiddle.net/4dTAG/1/
var rel = $('.navBulletsWrapper .active')[0].attributes.rel.value
答案 2 :(得分:1)
你不需要[0],因为只有一个.active
$('.navBulletsWrapper .active').attr('rel');
答案 3 :(得分:1)
$('.navBulletsWrapper .active')[0]
是一个html元素。
$('.navBulletsWrapper .active').eq(0)
是一个具有attr()
函数的jQuery元素。
答案 4 :(得分:1)
rel
属性不能与 div 一起使用
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel
最好使用 data-id="1"
类型属性
答案 5 :(得分:0)
本机:
document.querySelector('.navBulletsWrapper .active').getAttribute('rel');
jQuery的:
$('.navBulletsWrapper .active').attr('rel');