首页 > 解决方案 > 在“for”、“if”循环中的某些位置调用函数

问题描述

我正在尝试编写一个 JS 函数,该函数将遍历我的 HTML 文档中的元素,并对具有特定属性值(作为 值的特定 URL @href)的元素执行函数。但是,我无法将正确的元素传递给函数。

这是一个典型的 HTML 元素:

<a id="xyz" n="1" href="www.example.com">text</a>

该文件由其中许多组成。每个元素@id都是独一无二的。涉及<a>多个URL。@href这些不一定对应于@n属性值。所以它看起来像这样:

<html>
<head>
<title>MyDocument</title>
</head>
<body>
<a id="abc" n="1" href="www.example.com" onclick="myFunction(this.id)">text</a>
<a id="def" n="2" href="www.anotherexample.com" onclick="myFunction(this.id)">text</a>
<a id="xyz" n="1" href="www.example.com" onclick="myFunction(this.id)">text</a>
<a id="ghi" n="1" href="www.anotherexample.com" onclick="myFunction(this.id)">text</a>
</body>
</html>

我只对有@n属性的人感兴趣。

这是我的 JS 函数。这意味着将文档中具有相同@hrefURL 的所有元素传递到myOtherFunction.

function myFunction(id){
var el = document.getElementById(id);
var url= el.attributes[2].value;
var els = document.querySelectorAll("a[n]");
var i;
for (i = 0; i < els.length; i++) {
    if(els[i].attributes[2].value = url) {
        myOtherFunction(els[i].id);
    }
}
}

但是,它只传递<a>文档中的第一个元素,即使它没有@hreffrom 的值el

所以,想象一下<a>元素@id“def”被点击了。

预期结果 <a>元素@id“def”和@id“ghi”被传递给myOtherFunction.

当前结果 <a>元素@id“abc”被传递给“myOtherFunction”。

i调用中的变量myOtherFunction可能不会从“if”条件中保留其值。我将如何做到这一点?

或者我是否完全走上了错误的道路?

标签: javascripthtml

解决方案


<html>

<head>
    <title>a</title>
</head>

<body>
    
    <a id="xyz" n="1" href="www.example.com">text</a>

    <script>

        function myFunction(id) {
            var el = document.getElementById(id);
            //var url = el.attributes[2].value;
            var url = el.getAttribute('href')
            debugger
            var els = document.querySelectorAll("a[n]");
            var i;
            for (i = 0; i < els.length; i++) {
                if (els[i].getAttribute('href') == url) {
                    //myOtherFunction(els[i].id);
                }
            }
        }

        myFunction('xyz');
    </script>

</body>

</html>


推荐阅读