Reputation: 1963
I have a html like:
<div class="clicked-div" onclick="divClicked(this);">
<img src="src1"/>
<img src="src2"/>
......
</div>
if I set the img onclick event using the following method:
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onClick=imageClicked(imgs[i]);
}
function divClicked(div){
alert(div.getAttribute("id"));
}
function imageClicked(image){
alert(image.getAttribute("src"));
}
when the uiwebview load one image, it will call imageClicked a time though I haven't click it. And when I click a image ,how do I determing which method will be called divClicked or imageClicked? THank you.
Upvotes: 0
Views: 37
Reputation: 1074495
Your code is calling imageClicked
at the point you're trying to just set it up as a handler.
It's actually easier than you think it is:
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = imageClicked; // <=== Not *calling*, just referring to it
}
function imageClicked() {
alert(this.getAttribute("src")); // <== `this` rather than `image`
}
When imageClicked
is called in response to the click event, it's called with this
set to the image element that was clicked.
How to prevent the div to handle the click event when the image was clicked
Instead of onclick
, you use modern event handling and stop propagation. As you're using a uiWebView, you don't have to worry about old IE, which makes things simpler:
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("click", imageClicked, false);
}
function imageClicked(e) {
alert(this.getAttribute("src"));
e.stopPropagation(); // <=== Prevents the click reaching the div
}
Live example:
// Hook up the divs so we handle clicks on them
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].onclick = divClicked; // <=== Not *calling*, just referring to it
}
function divClicked() {
alert("div clicked");
}
// The images code
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("click", imageClicked, false);
}
function imageClicked(e) {
alert(this.getAttribute("src"));
e.stopPropagation();
}
<div>
<img src="https://www.gravatar.com/avatar/2cd48a51689add31036ce202cc020255?s=32&d=identicon&r=PG&f=1">
</div>
<div>
<img src="https://www.gravatar.com/avatar/760b4da77fd54d37c104029ff1f56749?s=32&d=identicon&r=PG">
</div>
<div>
<img src="https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG">
</div>
<div>
No image in this one, so you can see it handle clicks
</div>
Side note: Although you can use onClick
in your HTML, when you're using it in JavaScript, it has to be onclick
(all lower case). I've made that change above in the version that still used it.
Upvotes: 2