JQuery create elements and add event with .each () failed

The original html is just 2 hyperlinks.

I want

  • Add each button for each hyperlink.
  • when the click button shows each hyperlink value.
    if I press the first button, you will hear "ahref".
    if I press the second button, you will hear "bhref".

but the result is that both buttons warn 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>
+4
source share
2 answers

You need to use closure , for example:

$(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 -

, , each, . ., , :

$(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));
});
+5

google , "" , . .

1 "var", .
"var", , .
, , , .
"href" .
, .

href.

.

$(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);            
    });
});
0

Source: https://habr.com/ru/post/1616850/


All Articles