我正在尝试使用JavaScript修改页面中的链接。我可以选择div和a元素但不能更改href。
Shopify使用for循环生成这些对象,并且需要每个对象具有不同的链接。
这是HTML:
self
这是我的JavaScript。
<div id="tri-banner-1" class="banner-element banner-1 col-sm-4">
<a href="collections/all"><div class="home-banner">
<img src='//cdn.shopify.com/s/files/1/1093/4220/t/2/assets/group_top_banner01.png?17711418137279289271' alt="">
<div class="banner-caption">
<div class="display-table">
<div class="display-tablecell">
</div>
</div>
</div>
</div></a>
</div>
<div id="tri-banner-2" class="banner-element banner-2 col-sm-4">
<a href="collections/all"><div class="home-banner">
<img src='//cdn.shopify.com/s/files/1/1093/4220/t/2/assets/group_top_banner02.png?17711418137279289271' alt="">
<div class="banner-caption">
<div class="display-table">
<div class="display-tablecell">
</div>
</div>
</div>
</div></a>
</div>
<div id="tri-banner-3" class="banner-element banner-3 col-sm-4">
<a href="collections/all"><div class="home-banner">
<img src='//cdn.shopify.com/s/files/1/1093/4220/t/2/assets/group_top_banner03.png?17711418137279289271' alt="">
<div class="banner-caption">
<div class="display-table">
<div class="display-tablecell">
</div>
</div>
</div>
</div></a>
</div>
答案 0 :(得分:2)
banner1.getElementsByTagName("a");
返回HTMLCollection
。你应该使用索引选择元素; e.g;
// set `href` of first `a` element in `bannerLinks`
banner1Links[0].href = "facebook.com";
或迭代集合
for (var i = 0; i < bannerLinks.length; i++) {
bannerLinks[i] = /* set `href` here */;
}
答案 1 :(得分:0)
banner1Links获取一个数组值,因此您需要循环该数组,并为每个数组元素传递值
// instead of banner1Links.href="facebook.com";
for(var i = 0; i < banner1Links.length; i += 1){
banner1Links[i] = 'http://example.com';
}