单击图像以更改按钮的 url

Clicking an image to change the url of a button

如果有人点击所选商品的图片,图片下方的按钮url会发生变化

怎么办?
<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;
    }
}

这是一个代码笔http://codepen.io/anon/pen/bdyWGa

<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 变成什么

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。使用 e.target 获取当前点击元素并使用 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) ;
    }
}

CodeOpen

使用 jQuery 向所有图像添加点击事件以获取 属性 值并添加到目标元素的 href 属性

$(function(){
 $('img').on('click', function(){
   $('#buy').attr('href',"https://amazon.com/" + $(this).attr('value'));
 });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
<a id="buy" href="#"><button>Go to the the specific link</button></a>