将onclick事件添加到JavaScript中的新添加的元素 [英] Add onclick event to newly added element in JavaScript
问题描述
问题是当我检查document.body.innerHTML时,我可以看到onclick = alert('blah')被添加到新元素。
但是当我单击该元素时,我看不到警报框正在工作。事实上,与JavaScript有关的任何事情都不起作用。
这里是我用来添加新元素的:
function add_img(){
var elemm = document.createElement('rvml:image');
elemm.src ='blah.png';
elemm.className ='rvml';
elemm.onclick =alert('blah');
document.body.appendChild(elemm);
elemm.id =gogo;
elemm.style.position ='absolute';
elemm.style.width = 55;
elemm.style.height = 55;
elemm.style.top = 200;
elemm.style.left = 300;
elemm.style.rotation = 200;
}
这是我如何调用这个函数:
< button onclick = add_img()>添加图像< / button>
现在,图像在浏览器中完美展现。但是当我点击图像时,我没有得到这个警报。
.onclick
应该设置为一个函数而不是一个字符串。尝试
elemm.onclick = function(){alert('blah'); };
。
I have been trying to add onclick event to new elements I added with JavaScript.
The problem is when I check document.body.innerHTML I can actually see the onclick=alert('blah') is added to the new element.
But when I click that element I don't see the alert box is working. In fact anything related to JavaScript is not working..
here is what I use to add new element:
function add_img() {
var elemm = document.createElement('rvml:image');
elemm.src = 'blah.png';
elemm.className = 'rvml';
elemm.onclick = "alert('blah')";
document.body.appendChild(elemm);
elemm.id = "gogo";
elemm.style.position='absolute';
elemm.style.width=55;
elemm.style.height=55;
elemm.style.top=200;
elemm.style.left=300;
elemm.style.rotation=200;
}
Here is how I call this function:
<button onclick=add_img()>add image</button>
Now the image draws perfectly inside the browser. But when I click the image I don't get that alert.
.onclick
should be set to a function instead of a string. Try
elemm.onclick = function() { alert('blah'); };
instead.
这篇关于将onclick事件添加到JavaScript中的新添加的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!