selector in jquery - get rel attribute

2019-08-01 23:55发布

I have html code like this:

<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:

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

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

5条回答
ら.Afraid
2楼-- · 2019-08-02 00:13
$('.li').on('click', function(){
  var target = $(this).attr('rel');
});

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

查看更多
冷血范
3楼-- · 2019-08-02 00:18

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>
查看更多
趁早两清
4楼-- · 2019-08-02 00:23

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

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');
});
查看更多
爷、活的狠高调
5楼-- · 2019-08-02 00:23

Your all id are same.So make different them. Assuming that your li is inside ul which class is clsTest

$('.clsTest li').click(function(){
  var rel = $(this).attr('rel');
  alert(rel);
});
查看更多
The star\"
6楼-- · 2019-08-02 00:39

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

查看更多
登录 后发表回答