gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:27:15 25 4
gpt4 key购买 nike

我正在尝试编写一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com