4

The original html is only 2 hyperlink.

I want to

  1. Add each button behind each hyperlinks.
  2. when click button show each hyperlink value.
    if i click first button,will alert "ahref".
    if i click second button,will alert "bhref".

but result is both buttons alert "bhref".

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('a').each(function(){
            get_href=$(this).attr("href");
            new_ele = $("<button type='button'>test</button>");
            new_ele.click(function(){
                alert(get_href);
            });
            $(this).append(new_ele);
        });
    });
</script>
<body>
</body>
<a href="ahref" >a</a>      
<a href="bhref" >b</a>  
</html>

2 Answers2

5

You need to use some closure, e.g:

$(document).ready(function () {
    $('a').each(function () {
        var get_href = $(this).attr("href");
        var new_ele = $("<button type='button'>test</button>");
        (function (get_href) {
            new_ele.click(function () {
                alert(get_href);
            });
        })(get_href);
        $(this).append(new_ele);
    });
});

-jsFiddle-

Now, if you are facing this kind of issue regarding closure and each loop, usually there is better way of handling it. See e.g other way to get same expected behaviour:

$(document).ready(function () {
    var new_ele = $("<button type='button'>test</button>").on('click', function () {
        alert($(this).parent().attr('href'));
    });
    $('a').append(new_ele.clone(true));
});
Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

google a lot,"closure" is so hard to understand,too hard for me right now.but i figure it out in other way.

Only add 1 "var" make it work..
If define variable without 'var' ,means you define the global variable.
The global variable only has 1 reference, it means
If global variable change,all change.
Even if the "href value" at that moment was right.
If I treat the variables as objects,then everything make sense.

That why i always get the last href value.

I still new to this language.

$(document).ready(function () {
    $('a').each(function () {
        var get_href = $(this).attr("href");        
        new_ele = $("<button type='button'>test</button>");
        new_ele.click(function () {
            alert(get_href);
        });
        $(this).append(new_ele);            
    });
});