如何瞄准&仅使用父 div id 通过标签更改子元素?
使用常规 JavaScript(或原型),我尝试更改 div 中第一个也是唯一一个锚标记的 href 属性,以在 windows.location.search 末尾包含查询字符串。 div 有一个 id,而锚点是无类且无 id 的。我在其他地方看到过类似的代码,但不太正确。
到目前为止我所拥有的如下:
var divTag = document.getElementById("DivId").getElementsByTagName("a");
for(i = 0; i < divTag.length; i++){
divTags[i].href = "myUrl"+window.location.search;
}
我正在尝试处理的实际 html 代码:
<div id="DivId">
<a href="OldHref">
<img/>
</a>
</div>
谢谢。
Using regular JavaScript (or prototype), I'm trying to alter the href attribute of the first and only anchor tag within a div to include a query string at the end with windows.location.search. The div has an id, while the anchor is classless and id-less. I've seen similar code elsewhere, but its not quite right.
What I have so far is below:
var divTag = document.getElementById("DivId").getElementsByTagName("a");
for(i = 0; i < divTag.length; i++){
divTags[i].href = "myUrl"+window.location.search;
}
The actual html code I"m tryin to work on:
<div id="DivId">
<a href="OldHref">
<img/>
</a>
</div>
Thank You.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将变量声明为
divTag
,但将属性设置为divTags
。You declare the variable as
divTag
but set the attribute asdivTags
.您的代码基本上是正确的。您刚刚输入错误:
divTags[i].href = "myUrl"+window.location.search;
应该是:
divTag[i].href = "myUrl"+window.location .search;
单数而不是复数。
Your code is largely correct. You just made a typo:
divTags[i].href = "myUrl"+window.location.search;
Should be:
divTag[i].href = "myUrl"+window.location.search;
Singular instead of plural.