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 e开发者_StackOverflowvent 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.
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
Try addEventListener()
.
image.addEventListener('click',
function(e) {
RecordMouseClick(e, this.id);
}, false);
精彩评论