当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 'onClick' event on div not happening when there are child elements present

问题描述:

I'm building a new website for myself, looks like this..

HTML

<div id="row1">

<div class="orange" onClick="itemLoad()">

<img src="img/game/wacky.jpg" width="140" />

<p><strong>A Day At The Races (2014)</strong><br>

3 x 8-bit instruments</p>

</div>

<div class="blue" onClick="itemLoad()">

<img src="img/game/dott.jpg" width="140" />

<p><strong>Back to the Mansion! (2013)</strong><br />

fl, ob, cl, bsn, xyl, vibes, vln, vla, vlc.</p>

</div>

.... etc etc etc.

CSS (all boxes have identical CSS except the background colour)

.orange{

width:150px;

height:150px;

background:#F90;

display:inline-block;

margin:10px;

cursor:pointer;

box-shadow:#CCC 4px 4px 4px;

border-radius: 10px;

padding:10px;

font-family:Arial, Helvetica, sans-serif;

font-size:11px;

line-height:1.5;

}

Basically, when you click on one of the boxes, it shows a content DIV telling you about that piece of music, based on the row it's in.

JQuery

function itemLoad(){

if($(event.target).parent().is("#row1")){

$("#row1content").fadeIn("slow");

}else if($(event.target).parent().is("#row2")){

$("#row2content").fadeIn("slow");

}

}

This function works absolutely fine when the boxes are empty, but when they have content in them as you seen in the picture, the function only runs when I click around the padding. I've never had this problem before. Any help would be appreciated :)

网友答案:

event.target is the clicked element, and when you click a child element, that's what event.target is, so it's not consistently giving you the right element, or the right parent element, as event.target does not reference the element the event handler is bound to, but the element the event originated from.

Also, you're relying on the global event, which is not cross-browser.

What you want to do is use proper event handlers, and this

$('.blue, .orange').on('click', function() {
    if ( $(this).parent().is("#row1") ){
        $("#row1content").fadeIn("slow");
    } else if ( $(this).parent().is("#row2") ){
        $("#row2content").fadeIn("slow");
    }
});

It should be noted that there most definitively is a more dynamic way to do that, giving all the targeted elements the same class, and then fading based on index or position in the DOM, without targeting each element based on the parents ID.

网友答案:

This is what I had in mind :)

function itemLoad(event) {
    if ($(event.target).parents().is("#row1")) {
        $("#row1content").fadeIn("slow");
    } else if ($(event.target).parents().is("#row2")) {
        $("#row2content").fadeIn("slow");
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: