用按钮替换图像链接

时间:2018-05-01 06:15:06

标签: javascript jquery html

我非常喜欢使用javascript,我对这段代码有些疑问。 当我点击代码中的按钮时,我想替换我的图像链接。问题是我点击按钮之前已经替换了我的图片链接。这是代码。

function myFunction(parentID, size) {
    var parent = document.getElementById(parentID),
        image = parent.getElementsByTagName('img');
    for (var i = 0; i < image.length; i++) {
        image[i].src = image[i].src.replace(/\/s1600/, "/s" + size);
        image[i].width = size;
        image[i].height = size;
    }
}
myFunction('myDIV', 100);
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
<img src="http://2.bp.blogspot.com/-EmuHtKr11Jc/UFwUpHjrXAI/AAAAAAAABfk/LePqC5gLhwE/s1600/paksa-klik-ilkan.jpg">
</div>

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
function myFunction(parentID, size) {
    var parent = document.getElementById(parentID);
    var image = parent.getElementsByTagName('img');
    for (var i = 0; i < image.length; i++) {
        image[i].src = image[i].src.replace(/\/s1600/, "/s" + size);
        image[i].width = size;
        image[i].height = size;
    }
}
//this will directly call the function and make it a small sized image
//that is why your click does not work
//myFunction('myDIV', 100);
&#13;
<!--add params into click actions rather than the js above-->
<button onclick="myFunction('myDIV', 100)">Try it</button>
<div id="myDIV">
<img src="http://2.bp.blogspot.com/-EmuHtKr11Jc/UFwUpHjrXAI/AAAAAAAABfk/LePqC5gLhwE/s1600/paksa-klik-ilkan.jpg">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您立即调用该功能,而不是等待用户点击 - 删除该行。

此外,对于更易于维护的代码,请使用Javascript而不是HTML属性(与eval一样糟糕)附加侦听器:

&#13;
&#13;
document.querySelector('button').addEventListener('click', () => {
  myFunction('myDIV', 100);
});
function myFunction(parentID, size) {
  var parent = document.getElementById(parentID),
    image = parent.getElementsByTagName('img');
  for (var i = 0; i < image.length; i++) {
    image[i].src = image[i].src.replace(/\/s1600/, "/s" + size);
    image[i].width = size;
    image[i].height = size;
  }
}
&#13;
<button>Try it</button>
<div id="myDIV">
  <img src="http://2.bp.blogspot.com/-EmuHtKr11Jc/UFwUpHjrXAI/AAAAAAAABfk/LePqC5gLhwE/s1600/paksa-klik-ilkan.jpg">
</div>
&#13;
&#13;
&#13;