[英]How do I use elements from html in javascript for an onclick event?
[英]How do I declare event object with onclick event using Javascript (not html)?
这是我的代码:
function testimage() {
var image;
image = new Image();
with (image) {
id = "page1";
border = 0;
name = "IllustGIF";
useMap = "#MAP1";
src = "sample.gif" + "?d=" + new Date();
// The event argument here is invalid; it's to show what is the desired result.
onclick = function() { RecordMouseClick(event, this.id); };
}
// attached to body tag
document.getElementById("body_ID").appendChild(image);
}
function RecordMouseClick(event, id) {
alert("id: " + id + ", and event object should contain mouse x- and y- coordinates clicked");
}
我需要在JavaScript中定义onclick事件,而不是HTML。 现在在HTML中,它很简单 - 只需将事件作为参数传递给函数,然后将事件对象传递给JavaScript但是从头开始,所有这些都在JavaScript中,没有HTML,对我来说很有挑战性。 当调用引用函数时,它应该记录元素id,并且鼠标单击onclick事件中的x和y坐标。
如何将事件传递给onclick,以使事件对象在运行时有效?
谢谢。
这是一个小提琴样本 。
image.onclick = function(e) {
e = e || window.event;
RecordMouseClick(e, image.id);
};
document.getElementById('id-of-the-html-element').onclick = function(){
// your code
};
要么
function doSth(){
// your code
}
document.getElementById('id-of-the-html-element').onclick = doSth;
在这里阅读更多相关信息: https : //developer.mozilla.org/en/DOM/event
image.addEventListener('click',
function(e) {
RecordMouseClick(e, this.id);
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.