这是我的代码:
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,对我来说是一个挑战。当引用函数被调用时,它应该从 onclick 事件中记录元素 id 和鼠标点击 x 和 y 坐标。
如何将事件传递给 onclick,以便事件对象在运行时有效?
谢谢。
最佳答案
这是一个 sample fiddle .
image.onclick = function(e) {
e = e || window.event;
RecordMouseClick(e, image.id);
};
关于javascript - 如何使用 Javascript(不是 html)用 onclick 事件声明事件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7689442/