簡體   English   中英

如何使用Javascript(而不是html)使用onclick事件聲明事件對象?

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

這是我的代碼:

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,對我來說很有挑戰性。 當調用引用函數時,它應該記錄元素id,並且鼠標單擊onclick事件中的x和y坐標。

如何將事件傳遞給onclick,以使事件對象在運行時有效?

謝謝。

這是一個小提琴樣本

image.onclick = function(e) { 
    e = e || window.event;
    RecordMouseClick(e, image.id); 
};
document.getElementById('id-of-the-html-element').onclick = function(){
// your code
};

要么

function doSth(){
// your code
}

document.getElementById('id-of-the-html-element').onclick = doSth;

在這里閱讀更多相關信息: https//developer.mozilla.org/en/DOM/event

嘗試addEventListener()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM