jQuery '.each' and attaching '.click' event

后端 未结 2 1325
清酒与你
清酒与你 2020-12-12 23:35

I am not a programer but I enjoy building prototypes. All of my experience comes from actionScript2.

Here is my question. To simplify my code I would like to figure

相关标签:
2条回答
  • 2020-12-13 00:18

    One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

    For example:

    HTML:

    <body>
    <div id="dog" class="selected" data-selected="false">dog</div>
    <div id="cat" class="selected" data-selected="true">cat</div>
    <div id="mouse" class="selected" data-selected="false">mouse</div>
    
    <div class="dog"><img/></div>
    <div class="cat"><img/></div>
    <div class="mouse"><img/></div>
    </body>
    

    JS:

    $( ".selected" ).each(function(index) {
        $(this).on("click", function(){
            // For the boolean value
            var boolKey = $(this).data('selected');
            // For the mammal value
            var mammalKey = $(this).attr('id'); 
        });
    });
    
    0 讨论(0)
  • 2020-12-13 00:24

    No need to use .each. click already binds to all div occurrences.

    $('div').click(function(e) {
        ..    
    });
    

    See Demo

    Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

    0 讨论(0)
提交回复
热议问题