javascript - 在 "for"、 "if"循环中的某些位置调用函数

标签 javascript html

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

这是一个典型的 HTML 元素:

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

该文档由许多内容组成。每个@id其独特之处在于 <a>元素。多个@href涉及到URL。这些不一定对应于 @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 函数。这意味着使用相同的 @href 传递文档中的所有元素。网址为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>文档中的元素,即使没有 @href值来自 el

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

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

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

i myOtherFunction 调用中的变量可能不会保留“if”条件下的值。我怎样才能让它这样做呢?

或者我是否完全走在了我想做的事情的错误轨道上?

最佳答案

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

关于javascript - 在 "for"、 "if"循环中的某些位置调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51264521/

相关文章:

javascript - jQuery 迁移插件不允许我使用 jQuery(htmlString)

javascript - 对 5M 记录进行复杂字符串搜索的最佳方法是什么?应用层还是数据库层?

javascript - 使用 CSS 为跨度中的第 n 个字母设置样式

javascript - Google Analytics 代码返回 'Undefined Function"错误

javascript - 用于打印的 HTML 自动分页符

html - div 中的垂直对齐下拉列表

html - 使用溢出 :auto 的单元格创建可扩展表

html - 响应式网站 : What am I Missing?

javascript - Chrome 调试器中的这个十六进制值是什么意思?

javascript - 如何将网络摄像头捕获的图像路径存储在mysql数据库中