使用jquery循环遍历html页面的所有锚点标记

loop through all anchor tags of html page using jquery?

本文关键字:循环 jquery 遍历 html 使用      更新时间:2023-09-26

我想引用页面上所有具有的anchore标签

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

使用jquery将h2标记作为其父标记,为此,我必须通过具有父h2的每个锚标记,然后添加属性

onclick="callme();";

我正在使用点击的代码

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

但没有付出任何努力链接到fiddle是这个jsfiddle

感谢tobby的回答是正确的

selector(h2 + a)...

请参阅:https://jsbin.com/towejoqudu/edit?html,js,控制台,输出

我已经在你的锚中添加了文本,这样你就可以点击它们了。

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

您可以通过绑定到主体一次(事件委派)来避免所有不必要的遍历,如下所示:

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