如果某人点击所选产品的图片以更改图片下按钮的网址,我该怎么做?
<div id="product">
<img value="1" src="http://placehold.it/300x100?text=Mary+Jane" alt="" />
<img value="2" src="http://placehold.it/300x100?text=LSD" alt="" />
<img value="3" src="http://placehold.it/300x100?text=Crack" alt="" />
</div>
<br>
<a id="buy" href="#"><button>Go to the the specific link</button></a>
text / image仅供娱乐,它们不是真正的产品
我尝试了什么
window.onload = function() {
var sel = document.getElementById('product');
sel.onchange = function() {
document.getElementById("buy").href = "https://amazon.com/" + this.value;
}
}
这是一个codepen http://codepen.io/anon/pen/bdyWGa
答案 0 :(得分:2)
Jquery解决方案:
$(function(){
$("img").click(function(){
$("#buy").attr("href","https://amazon.com/"+$(this).attr("value"));
});
});
Javascript版本:
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
img = images[i];
img.addEventListener("click", function() {
document.getElementById("buy").setAttribute("href", "https://amazon.com/"+ this.getAttribute("value"));
alert("New href value: " + "https://amazon.com/"+ this.getAttribute("value"));
});
}
答案 1 :(得分:0)
<img id="img1" src="http://placehold.it/300x100?text=Mary+Jane" alt="" />
<img id="img2" src="http://placehold.it/300x100?text=LSD" alt="" />
<img id="img3" src="http://placehold.it/300x100?text=Crack" alt="" />
<br>
<a id="buy" href="#"><button>Go to the the specific link</button></a>
和
$("#img1").on("click", function(){
$("#buy").attr("href","https://mynewurl.net");
});
在这里,您描述了点击哪个img会将URL更改为
答案 2 :(得分:0)
在javascript中。使用e.target
获取当前的click元素并使用attrubutes获取值并应用于href属性。
window.onload = function() {
var sel = document.getElementById('product');
sel.onclick = function(e) {
console.log( e.target.attributes[0].value)
document.getElementById("buy").setAttribute('href', "https://amazon.com/" + e.target.attributes[0].value) ;
}
}