如何使用 Javascript(不是 html)通过 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 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,以便事件对象在运行时有效?
谢谢。
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. 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. 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.
How can I pass an event to the onclick, such that the event object is valid at run-time?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个示例小提琴。
Here's a sample fiddle.
或者
在这里阅读更多相关信息:https://developer.mozilla.org/en/DOM/event
or
Read more about it over here: https://developer.mozilla.org/en/DOM/event
尝试
addEventListener()
。Try
addEventListener()
.