我在使用 jquery 选择元素属性时遇到了问题,这里是我的 HTML:
<a class="myselector" rel="I need this value"></a>
<div class="someClass" id="someID">
...bunch of elements/content
<input type="button" name="myInput" id="inputID" title="myInput Title" />
...bunch of elements/content
</div>
...一堆元素/内容
我在这里尝试获取 myselector 的 rel 值,这是我尝试的方式,但它不起作用:
$('#inputID').live('click',function(){
console.log($(this).closest('a.myselector').attr('rel'));
});
也尝试过这个,因为所有内容都包装在包装器 div 中:
$('#inputID').live('click',function(){
console.log($(this).parent('div.wrapper').find('a.myselector').attr('rel'));
});
在这两种情况下,我都在 firebug 中得到了 undefined
值,我使用 live 因为 div#someID
被加载到文档中,它在页面首次加载时不存在。任何建议,我怎样才能得到我的选择器相对值?
编辑:
然而,当我寻找没有 rel 属性的 ('a.myselector')
时,我会提醒 Object object
并获取 console.log 内容 []
最佳答案
这应该有效:
console.log($(this).closest('div.wrapper').find('a.myselector').attr('rel'));
问题中的第一个示例不起作用,因为您尝试选择的 anchor 标记是 not a parent/ancestor:
console.log($(this).closest('a.myselector').attr('rel'));
如果您将 .parent()
更改为 .parents()
,您的第二个示例将起作用,因为 .parent()
仅遍历 one level向上 DOM,所以如下:
console.log($(this).parents('div.wrapper').find('a.myselector').attr('rel'));
关于javascript - jquery 选择器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2708355/