简体   繁体   中英

How do i get the value of an attribute for all elements dynamically using Jquery?

hey there, I have a Navigation Menu and my code looks like this..

    <ul id="nav">
        <li><a href = "#countries" >Countries</a></li>
        <li><a href = "#states" id="">States</a></li>
        <li><a href = "#cities">Cities</a></li>
        <li><a href = "#areas">Areas</a></li>
    </ul>

i would want to fetch all the attributes values dynamically depending on the user click for example if the user clicks on Countires it should fetch the value #countries, if the user clicks on states it should fetch the value #states and so on.

i am aware of the .attr() in jQuery. the functions only fetches the first element in the set of matched elements. no matter wherever i click it will fetch only #countries. i do not want to be this case.

i am using the following jquery code.

<script type="text/javascript">
$(document).ready(function(){
    //when the user clicks on Navigation Menu call this function
    $('ul#nav li a').click(function(){
        //fetch the attribute value.
        $value = $('ul#nav li a').attr("href");
        alert($value);

        //Stop the default behaviour
        return false;
    });
});
</script>

How do i fetch all the attribute value dynamically and store the value in different variable?

This will do the trick:

var $value = $(this).attr('href');

Inside the click handler, the this value refers to the element that has been clicked.

Change this line:

$value = $('ul#nav li a').attr("href");

To this:

var $value = $(this).attr('href');

Or even just this:

var $value = this.getAttribute('href');

(Note that the implementation of getAttribute in IE6 and IE7 is broken.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM