最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery: event listener for array of elements - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Dec 25, 2013 at 3:36 asked Dec 25, 2013 at 3:24 user1890615user1890615 4
  • why do you want to create an array – Arun P Johny Commented Dec 25, 2013 at 3:27
  • jQuery already creates an array of elements when you do $(selector) – charlietfl Commented Dec 25, 2013 at 3:30
  • Yes, but I only want a portion of those elements. – user1890615 Commented Dec 25, 2013 at 3:31
  • @cinderblock it can be accessed by using attribute selectors... see my answer below – Arun P Johny Commented Dec 25, 2013 at 3:32
Add a ment  | 

5 Answers 5

Reset to default 5

Use jQuery's map function to join your array elements into a single bined 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 biObj = $.map(elements, function(el){return el.get()});
$(biObj).on('click', function(ev){
	console.log('EVENT TRIGGERED');
});
button{
  display: block;
  margin: 10px;
}
<script src="https://ajax.googleapis./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>

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
})

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

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

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({...});

I would've just added a ment on what Girish said, but since I don't have enough reputation yet, here's my addition to Girish's answer.

I just want to add that if you want to add an event listener to an array of buttons, with each button having an image in it, just using Event.target to access the buttons might cause a problem, because the image inside the button may bee the event target if the image is clicked on. Try clicking on the image and around the image in the snippet below. When the image is clicked on, the event target is the image, not the button.

Check it out:

$('button').click(e => $('#eventTarget').text(e.target));
/*just random styling to make things a little clearer. not important*/
button {
  padding: 20px;
}
button img {
  height: 50px;
}
div {
  padding: 20px;
  background: #eee;
  margin-top: 10px;
  width: 200px;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>
 <img src="https://cdns.iconmonstr./wp-content/assets/preview/2013/240/iconmonstr-trash-can-1.png" alt="">
</button>

<div id="eventTarget"></div>

To circumvent this, remove all pointer events from the image within the button, so that only the button can be the event target.

Use this CSS to avoid the above issue:

button img {
  pointer-events: none;
}
发布评论

评论列表(0)

  1. 暂无评论