简体   繁体   English

大量容器Div中的div的OnClick事件

[英]OnClick event for div inside lots of container Divs

I have an app I'm developing and I need a onclick() event to be fired when a <div> is clicked. 我有一个正在开发的应用程序,单击<div>时需要触发onclick()事件。

So in other words, 换句话说,

<div id="panda"></div>

 $("#panda").click(function () {
        console.log("some text");
    });

So this statement works but now lets say I have, 因此,此语句有效,但现在让我说,

    <div id="panda">
    <lots of children>
     <div id="koala">
    </div>
    </lots of children>
    </div>


 $("#koala").click(function () {
        console.log("doesnt work");
    });

Now you see for the life of me I can't get koala to be clickable. 现在,您看到了我的一生,我无法让无尾熊变得可点击。 The click event on parents works fine, and click evens for some empty divs I use as buttons work fine, but for some reason I cant get I filled child <div> to be clickable. 父母的click事件工作正常,对于用作按钮的某些空div的单击事件也可以正常工作,但是由于某些原因,我无法让孩子填写<div>使其可单击。

Any ideas what the case could be? 任何想法可能是什么情况?

I tried this, 我试过了

 $('#panda').click(function(e){
        if ($(e.target).is('#koala'))
        {
            console.log("koala");
        }

    });

But it just logs every click on the parent. 但这只会记录对父项的每次点击。

One option is to listen to the div children for panda . 一种选择是听div孩子讲panda

 $("#panda").on('click','div',function() { console.log($(this).text()+' '+$(this).attr('id')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="panda"> <div id="koala"> koala </div> <div id="bear"> bear </div> </div> 

Try making the selector '#panda #koala' like this 尝试使选择器像这样#panda #koala

$("#panda #koala").click(function () {
        console.log("koala");
    });

Here is an example, 这是一个例子

<div id="panda">Panda
    <div id="koala">Koala</div>
</div>

$("#panda").on('click', '#koala', function () {
    alert("koala!!!");
});

Here is a Fiddle 这是小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM