Jquery:元素数组的事件监听器 [英] Jquery: event listener for array of elements

查看:460
本文介绍了Jquery:元素数组的事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .each()方法和 $(this)选择器填充包含元素的数组。

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.

例如:

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

我想onclick属性可以在每个图像循环时改变,但是这似乎有些不确定。我想确定这是我实施之前的最后手段。

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.

推荐答案

不需要数组,您可以使用元素选择器以及具有属性选择器以获取具有给定属性的所有图像元素,然后使用。click()注册事件处理程序

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

这篇关于Jquery:元素数组的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆