jquery 中的选择器 - 获取 rel 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11720069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:52:27  来源:igfitidea点击:

selector in jquery - get rel attribute

jqueryjquery-selectors

提问by kamal

I have html code like this:

我有这样的html代码:

<li id="vol" rel="1">
    // something here
</li>
<li id="vol" rel="2">
    // something here
</li>
<li id="vol" rel="3">
    // something here
</li>

I'm try to get rel attribute by this code:

我尝试通过此代码获取 rel 属性:

$('#vol').click(function(){
  var rel = $(this).attr('rel');
});

But it's not working. I also change thisto #vol, but it didn't work. What should i do?

但它不起作用。我也this改为#vol,但它没有用。我该怎么办?

回答by Andreas Wong

By Not working, I'm assuming that any liyou click, gives you back 1, this is caused by having multiple ID in a page. IDs are supposed to be unique, use class instead.

通过不工作,我假设li您单击任何内容都会返回1,这是由于页面中有多个 ID 造成的。ID 应该是唯一的,请改用类。

try

尝试

<li class="vol" rel="1">
    // something here
</li>
<li class="vol" rel="2">
    // something here
</li>
<li class="vol" rel="3">
    // something here
</li>

JS:

$('.vol').click(function(){
  var rel = $(this).prop('rel');
});

回答by Shree

Your all idare same.So make different them. Assuming that your liis inside ulwhich class is clsTest

你们都是id一样的,所以让他们不同。假设你liul哪个班级里面clsTest

$('.clsTest li').click(function(){
  var rel = $(this).attr('rel');
  alert(rel);
});

回答by coolguy

Change your code to

将您的代码更改为

<li class="vol" rel="1">
    // something here
</li>
<li class="vol" rel="2">
    // something here
</li>
<li class="vol" rel="3">
    // something here
</li>

<script>
$('body').delegate('li.vol','click',function(){
  var rel = $(this).attr('rel');
});
</script>

回答by Bekzat Abdiraimov

Selector by "id" (#id) select only one element, use "class" (.class) instead

Selector by "id" (#id) 只选择一个元素,使用 "class" (.class) 代替

回答by mano

$('.li').on('click', function(){
  var target = $(this).attr('rel');
});

i think we directly try with element if you have using li

如果您使用 li,我想我们直接尝试使用 element