admin管理员组文章数量:1328592
<ul class="dropdown-menu" id="parent">
@foreach($cat as $category)
<li class="dropdown-submenu">
<a id={{$category->id}}>{{$category->category_name}}</a>
</li>
@endforeach
This is my script And it always give me the same value that is 1
I want always change value that es from database
$("#parent li a").click(function(){
var id = $('#parent li a').attr('id');
alert(id);
});
<ul class="dropdown-menu" id="parent">
@foreach($cat as $category)
<li class="dropdown-submenu">
<a id={{$category->id}}>{{$category->category_name}}</a>
</li>
@endforeach
This is my script And it always give me the same value that is 1
I want always change value that es from database
$("#parent li a").click(function(){
var id = $('#parent li a').attr('id');
alert(id);
});
Share
Improve this question
edited Sep 22, 2017 at 13:39
Kristianmitk
4,7785 gold badges29 silver badges49 bronze badges
asked Sep 22, 2017 at 13:32
Arslan AkramArslan Akram
3601 gold badge5 silver badges25 bronze badges
3
- 1 var id = $(this).attr('id'); – okante Commented Sep 22, 2017 at 13:35
-
.attr()
will get the value of an attribute for the first element in the set of matched elements. and you can find it out on Jquery API api.jquery./attr – shanechiu Commented Sep 22, 2017 at 13:56 - @Arslan Akram, please accept the best answer among all. – Himanshu Upadhyay Commented Sep 22, 2017 at 13:59
4 Answers
Reset to default 7Change your jQuery function like this:
$("#parent li a").click(function(){
var id = $(this).attr('id'); // use `this`
alert(id);
});
Note
The code you have used var id = $('#parent li a').attr('id');
will always consider the 1st <a>
of the 1st <li>
which was wrong.
this
will refer to the element which was clicked. Hence you would get the correct value.
value that es from database
I would remend you to use data-*
custom attribute to persists arbitrary data which can be fetched using .data(key)
in the current element context this.
$("#parent li a").click(function(){
var id = $(this).data('id');
});
<li class="dropdown-submenu">
<a data-id="{{$category->id}}">{{$category->category_name}}</a>
</li>
Within the click
event you can use $(this)
as the clicked element:
$('#parent li a').click(function() {
var id = $(this).attr('id');
alert(id);
});
If you use within your click handler the this
reference - which is in this case the clicked element, than you can access the proper id
attribute you are looking for.
$("#parent li a").click(function(){
var id = $(this).attr('id');
alert(id);
});
本文标签: javascriptHow to get a dynamic attribute valueStack Overflow
版权声明:本文标题:javascript - How to get a dynamic attribute value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742257510a2441898.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论