Jquery: event listener for array of elements

2020-04-12 04:23发布

问题:

I am populating an array with elements using the .each() method and $(this) selector.

(function($){

    var elements = new Array();
    var index = 0;
    $("img").each(function() {
        if($(this).attr("attribute")){
            $(this).attr("imageIndex", index);
            elements[index] = $(this);
            index++;
        }
    });

}(jQuery));

I would like to add an event listener to my code that is executed when any element in that array is clicked.

For example:

$(elements).click = function(){
    console.log("success");
}

I suppose the onclick attribute could be changed as each image is looped through, but this seems somewhat inconcise. I would like to be certain that that is my last resort before I implement it.

回答1:

There is no need of an array, you can use the element selector along with has attribute selector to get all image elements with the given attribute, then use .click() to register the event handler

$("img[attribute]").click(function(){
    //do your stuff
})


回答2:

Use jQuery's map function to join your array elements into a single combined jQuery object.
Then attach jQuery events to this object (using "on()" in this example).

var elements = [$('#blah'), $('#blup'), $('#gaga')];  //basically what you are starting with

var combiObj = $.map(elements, function(el){return el.get()});
$(combiObj).on('click', function(ev){
	console.log('EVENT TRIGGERED');
});
button{
  display: block;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="blah">Button blah</button>
<button id="blup">Button blup</button>
<button id="gaga">Button gaga</button>



回答3:

Use a comma separated list of selectors, wrapped in quotes like so:

$('#id, .selector, .somethingElse').click(function() {
    //your handler
});


回答4:

There not required to store Objects in array, you can get current event this way

<script type="text/javascript">
     $(function(){
        $("img").bind("click", function(Event){
            console.log(Event.target);
         });
     })
</script>

when you click on any image element, you will get current event target inside function "Event.target" or you can use also this way $(Event.target).fun({...});