如果有人点击所选产品的图像来更改图像下按钮的网址,我该如何做到这一点
<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>
文字/图像仅供娱乐,它们不是真正的产品
我尝试过的
window.onload = function() {
var sel = document.getElementById('product');
sel.onchange = function() {
document.getElementById("buy").href = "https://amazon.com/" + this.value;
}
}
最佳答案
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"));
});
}
工作 fiddle :http://codepen.io/anon/pen/NqVjGY
关于javascript - 单击图像以更改按钮的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32053513/