javascript - 在“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 函数。这意味着将文档中具有相同@href
URL 的所有元素传递到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
from 的值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>
推荐阅读
- android - 将 java 本机包导入 react-native 项目
- java - CompletableFuture:等待完成百分比
- sql - 在 SQL Developer 中减去投射日期 (EPOCH) 时如何删除小数
- azure-devops - Azure DevOps 为多个 YMLS 构建最佳实践
- laravel - 使用 vue js 时 Laravel 路由不起作用
- laravel - 无法使用 Laravel 和 Xampp 进行迁移
- java - Reactor SubscriberContext 不适用于 ServerRequest 正文
- python - TypeError:在Python中使用不和谐机器人发送数据时没有字符串参数的编码
- android - NextCloud Android 应用程序:NC 密码,无法通过“授予”
- java - JAVA 将日期字符串转换为日期对象