简体   繁体   中英

loop through all anchor tags of html page using jquery?

i want to refrence all anchore tags on page that have

<body>
    <h1>not me</h1>
    <a href ="google.com"></a>
    <h1>not me also </h1>
    <a href ="fb.com"></a>

    <h2>me also as i am H2 </h2>
    <a href ="FIDDLE.com"></a>
    <h3>not me also </h3>
    <a href ="fbO.com"></a>
    <h2>me also as i am H2 </h2>
    <a href ="FIDDLE2.com"></a>

    <button onclick="score2Dmatrix();" id="btn" ></button>

h2 tag as their parent using jquery , for that i have to pass through each anchor tag that have parent h2 and then add attribute

onclick="callme();";

i am using that code onclick

<script>      
function callme() {
    $("h2 a").each(function () {
    $(this).attr("onclick", "score2Dmatrix();");
    });
};
</script>

but no effort link to fiddle is this jsfiddle

thanks for that tobby answers is right

selector(h2 + a)...
$('h2').find('a').on('click', callme);

You can avoid all of the unnecessary traversal by binding to the body once (event delegation), like so:

$('body').on('click', 'a', function(){
    var $clicked = $(this);
    if($clicked.closest('h2').length){
        callme();
    }
});

Please see: https://jsbin.com/towejoqudu/edit?html,js,console,output

I have added text into your anchors so you can actually click them.

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