如何使用 Javascript(不是 html)通过 onclick 事件声明事件对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7689442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:11:51  来源:igfitidea点击:

How do I declare event object with onclick event using Javascript (not html)?

javascripteventsfunctionreferenceonclick

提问by user717236

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.

我需要在 JavaScript 中定义 onclick 事件,而不是 HTML。现在在 HTML 中,这很容易——只需将 event 作为参数传递给函数,瞧,JavaScript 中的 event 对象但是从头开始,全部使用 JavaScript,没有 HTML,对我来说是一个挑战。当引用函数被调用时,它应该记录元素 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.

谢谢你。

回答by canon

Here's a sample fiddle.

这是一个示例小提琴

image.onclick = function(e) { 
    e = e || window.event;
    RecordMouseClick(e, image.id); 
};

回答by js-coder

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

回答by Chad

Try addEventListener().

试试addEventListener()

image.addEventListener('click', 
    function(e) { 
        RecordMouseClick(e, this.id); 
    }, false);