怎么为动态生成的html元素增加事件处理
本文主要介绍"如何为动态生成的html元素增加事件处理",希望能够解决您遇到有关问题,下面我们一起来看这篇 "如何为动态生成的html元素增加事件处理" 文章。
function klik()...{
alert("ppp");
}
function addNewImg(newImageId)...{
newImg = document.createelement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
newImg.onclick=klik
}
it works. The new image is created and after clicking on it "ppp" is alerted.
but when I use this:
function klik(ff)...{
alert(ff);
}
function addNewImg(newImageId)...{
newImg = document.createelement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
newImg.onclick=klik("ppp");
}
"ppp" is alerted in the moment of executing the statement newImg.onclick=klik("ppp"); and when clicking on the generated image nothing happens, even Javascript Console of Firefox stays blind.
function addNewImg(newImageId)...{
newImg = document.createelement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
var onC='ppEdit("image'+newImageId+'","image")';
document.getElementById("image"+newImageId).onclick=new Function(onC);
}
it works
maybe an object detection be great to add too
why?
So browsers that understand document.getElementById,
document.createelement execute the code.
function addNewImg(newImageId)...{
//object detection check
if (!document.getElementById &&!document.createelement)...{return;}
newImg = document.createelement('img');
newImg.id = "image"+newImageId;
newImg = document.getElementById("divimage1").appendChild(newImg);
var onC='ppEdit("image'+newImageId+'","image")';
document.getElementById("image"+newImageId).onclick=new Function(onC);
}
alternative solution:
if (!document.getElementById) ...{return;}
document.getElementById("image"+newImageId).onclick=function()...{
ppEdit(this.id, "image");
}
关于 "如何为动态生成的html元素增加事件处理" 就介绍到这。希望大家多多支持编程宝库。
本文主要介绍"html相对路径的写法介绍",希望能够解决您遇到有关问题,下面我们一起来看这篇 "html相对路径的写法介绍" 文章。 HTML是一种规范,一种标准,它通过标记符号来标记要显示的网页中的各个部分。 ...