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
Add a ment  | 

4 Answers 4

Reset to default 7

Change 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