Javascript getElementById <img>
i was wondering if there is a way to acess an image's onclick开发者_运维百科 property by using getElementById?
e.g.
lastTopic = document.getElementById('topicID').src;
lastTitle = document.getElementById('topicID').title;
these vars are stored so i was wondering if there is a way to access the related onclick event also?
thanks.
Sure, to set the onclick property:
document.getElementById('topicID').onclick = function () {
...
};
Or to get it:
alert(document.getElementById('topicID').onclick);
It's important to remember what onclick
actually is: It's an attribute (and a reflected property) that can be used to attach a handler to the click
event using the old, "DOM0" (e.g., never-standardized) mechanism.
If you are attaching a click
handler using a standardized mechanism like addEventListener
or IE's near-equivalent attachEvent
, onclick
will remain null
or undefined
because those are not assigned to the onclick
attribute or property.
Here's an exploration of this diffrence (live example):
HTML:
<p>This one has an onclick:
<img src='http://www.gravatar.com/avatar/0f1f6b8a8416c6cf0a97cfc864889788?s=32&d=identicon&r=PG' id='dom0img' onclick='dom0click(this);'></p>
<p>This one has a DOM2 click handler:
<img src='http://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG' id='dom2img'></p>
JavaScript:
window.onload = function() {
var dom0img, dom2img;
dom0img = document.getElementById('dom0img');
dom2img = document.getElementById('dom2img');
if (dom2img.addEventListener) {
dom2img.addEventListener('click', dom2click, false);
display("Attached DOM2-style handler to dom2img via addEventListener");
}
else if (dom2img.attachEvent) {
dom2img.attachEvent('onclick', dom2click);
display("Attached DOM2-style handler to dom2img via attachEvent");
}
else {
display("Can't attach DOM2-style handler to dom2img");
}
display("dom0img.onclick = " + dom0img.onclick);
display("dom2img.onclick = " + dom2img.onclick);
};
function dom0click(img) {
display("DOM0 click on " + img.id);
}
function dom2click() {
display("DOM2 click on " + this.id);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
Output on Chrome:
Attached DOM2-style handler to dom2img via addEventListener dom0img.onclick = function onclick(event) { dom0click(this); } dom2img.onclick = null
Output on IE6 and IE8:
Attached DOM2-style handler to dom2img via attachEvent dom0img.onclick = function anonymous() { dom0click(this); } dom2img.onclick = null
Output on Firefox:
Attached DOM2-style handler to dom2img via addEventListener dom0img.onclick = function onclick(event) { dom0click(this); } dom2img.onclick = undefined
you can get any DOM attribute value using element.getAttribute(attributeName) method.
As @box9 said, you need to bind onclick event dynamically or through onclick attribute in image tag.
精彩评论