[英]Add OnClick Function to newly created image that
I'm needing to dynamicly add a onclick that can focus on itself so when clicked it will add the width and remove it我需要动态添加一个 onclick 可以专注于自身,所以当点击它会添加宽度并删除它
function addimage2(where) {
var img = document.createElement("img");
img.src = "swatch.jpg";
img.width = 300;
where.parentNode.appendChild(img);
}
old method旧方法
<img src="swatch.jpg" alt="swatch-sm" onClick="addimage2(this);">
I need it like this as new images are created dynamicly我需要这样,因为新图像是动态创建的
img.onclick = function(this){
if(this.width == 300) {
this.removeAttribute("width");
}else{
this.setAttribute("width","300");
}
}
Simply say简单地说
img.addEventListener("click",addimage2);
If you need to pass parameters to addimage2
then use the following:如果您需要向
addimage2
传递参数,请使用以下命令:
img.addEventListener("click",event => {
addimage2(parameters,here);
});
If you're going to be adding a bunch of these things, may I suggest a single delegated event listener, then you can add more images later and they will "just work".如果您要添加一堆这些东西,我可以建议一个委托事件侦听器,然后您可以稍后添加更多图像,它们将“正常工作”。 All you need to do is assign a class to all of the images you want to treat this way.
您需要做的就是将 class 分配给您要以这种方式处理的所有图像。
document.addEventListener("click", (e) => { const el = e.target; if (el.classList.contains("resizey")) { if (el.width == 300) { el.removeAttribute("width"); } else { el.setAttribute("width","300"); } } }, true); // true to use capture
<img class='resizey' src='https://upload.wikimedia.org/wikipedia/commons/3/3f/A_small_loch_in_the_saddle_between_Beinn_an_Dothaidh_and_Beinn_Dorain%2C_Scotland_01.jpg' /> <img class='resizey' src='https://upload.wikimedia.org/wikipedia/commons/9/94/Techumbre_mud%C3%A9jar%2C_Catedral%2C_Teruel%2C_Espa%C3%B1a%2C_2014-01-10%2C_DD_38.JPG' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.