我对下面的代码和通过更改 www.w3schools.com 上的示例生成的结果感到困惑。具体来说,当链接是某个父级的子级时,我不明白为什么parent.children 返回 href
的值当元素是<a>
时标签?
<!DOCTYPE html>
<html>
<body>
<a href="http://www.example.com/my.jpg"></a>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var c = document.body.children;
var txt = "";
var i;
for (i = 0; i < c.length; i++) {
txt = txt + c[i] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
上面的代码提供了以下结果,第一个结果是我没有预料到的。
http://www.example.com/my.jpg
[object HTMLButtonElement]
[object HTMLParagraphElement]
[object HTMLScriptElement]
所以不要列出 <a>
标签作为对象,而是给出 href 属性的值。
我正在开发 blueimp gallery https://github.com/blueimp/Gallery 的实现。用户选择缩略图,就会弹出一个轮播灯箱,初始化为相应的高分辨率照片。我正在研究 iphone 特定问题并边学习代码边进行。
最佳答案
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement#Methods :
HTMLHyperlinkElementUtils.toString()
Returns a
USVString
containing the whole URL. It is a synonym forURLUtils.href
, though it can't be used to modify the value.
换句话说,当您将 anchor 元素转换为字符串时,您将获得 href
属性的内容。
顺便说一下,这个功能(a
元素字符串化为其href
值,而不是[object HTMLSomethingElement]
)已被用来绕过安全检查:
https://bugs.chromium.org/p/project-zero/issues/detail?id=1225&desc=6 LastPass:可以跨隔离世界修改全局属性,允许远程代码执行
关于包含链接的 div 的 Javascript dom 子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51736514/