[英]How do I declare event object with onclick event using Javascript (not html)?
Here is my code: 这是我的代码:
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");
}
I need to define the onclick event in JavaScript, not HTML. 我需要在JavaScript中定义onclick事件,而不是HTML。 Now in HTML, it's easy -- just pass event as an argument to the function and, voila, event object in JavaScript But doing it all from scratch, all in JavaScript, without HTML, is challenging for me.
现在在HTML中,它很简单 - 只需将事件作为参数传递给函数,然后将事件对象传递给JavaScript但是从头开始,所有这些都在JavaScript中,没有HTML,对我来说很有挑战性。 When the reference function is called, it's supposed to record the element id and the mouse click x- and y- coordinates from the onclick event.
当调用引用函数时,它应该记录元素id,并且鼠标单击onclick事件中的x和y坐标。
How can I pass an event to the onclick, such that the event object is valid at run-time? 如何将事件传递给onclick,以使事件对象在运行时有效?
Thank you. 谢谢。
Here's a sample fiddle . 这是一个小提琴样本 。
image.onclick = function(e) {
e = e || window.event;
RecordMouseClick(e, image.id);
};
document.getElementById('id-of-the-html-element').onclick = function(){
// your code
};
or 要么
function doSth(){
// your code
}
document.getElementById('id-of-the-html-element').onclick = doSth;
Read more about it over here: https://developer.mozilla.org/en/DOM/event 在这里阅读更多相关信息: https : //developer.mozilla.org/en/DOM/event
Try addEventListener()
. 尝试
addEventListener()
。
image.addEventListener('click',
function(e) {
RecordMouseClick(e, this.id);
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.