如何使用Javascript(而不是html)通过onclick事件声明事件对象?
这是我的密码:如何使用Javascript(而不是html)通过onclick事件声明事件对象?,javascript,events,function,reference,onclick,Javascript,Events,Function,Reference,Onclick,这是我的密码: 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 inva
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而不是HTML定义onclick事件。现在在HTML中,这很简单——只需将事件作为参数传递给函数,瞧,JavaScript中的事件对象,但从头开始,全部用JavaScript,不使用HTML,这对我来说是一个挑战。调用reference函数时,应该记录元素id以及onclick事件中的鼠标单击x和y坐标
如何将事件传递给onclick,使事件对象在运行时有效
谢谢。试试看
或
请在这里阅读更多信息:这里有一个例子
非常感谢你的帮助。我很感激这个链接和解决方案。谢谢。我已经更新了fiddle,以解决firefox的
clientX
与x
的点击事件坐标问题。
image.addEventListener('click',
function(e) {
RecordMouseClick(e, this.id);
}, false);
document.getElementById('id-of-the-html-element').onclick = function(){
// your code
};
function doSth(){
// your code
}
document.getElementById('id-of-the-html-element').onclick = doSth;
image.onclick = function(e) {
e = e || window.event;
RecordMouseClick(e, image.id);
};