如何使用jQuery中的循环自动绑定多个事件处理程序 [英] How to automatically bind multiple event handlers with a loop in jQuery

查看:75
本文介绍了如何使用jQuery中的循环自动绑定多个事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个模拟棋盘的简单应用程序。因此我有一个64个方格的桌子。我想通过编写一个循环而不是写出64次的函数来为每个方块绑定事件处理程序。编辑:请注意我希望处理程序返回一个数字值来指示单击了哪个div。我不需要处理程序来返回div的内容。这是给出两个可点击的div的简化版本:

I am working on a simple app that simulates a chess board. Therefore I have a table with 64 squares. I would like to bind event handlers for each square by writing a single function that goes through a loop instead of writing things out 64 times. Please note I want the handlers to return a numeric value to indicate which div was clicked. I don't need the handlers to return the content of the divs. Here is a simplified version given two clickable divs:

<div id="div0">A box</div>
<div id="div1">Another box</div>
<div id="say"></div> 

和javascript代码:

and the javascript code:

$("#say").append("Which div are you going to click? ");

function clicky() {
    var i = 0;
    while (i < 2) {
        $("#div" + i).on("click", function () {
            $("#say").append("div" + i);
        });
        i++;
    }

}

clicky();

这是的jsfiddle

该函数几乎可以工作,也就是说,它绑定到两个div,但是它将相同(错误)的处理程序绑定到它们。不知道如何解决这个问题。

The function almost works, that is, it binds to both divs, but it binds the same (wrong) handler to both of them. Not sure how to fix this.

推荐答案

使用公共类。然后,您可以使用类选择器(.class)绑定事件

Use a common class. Then you can use Class Selector (".class") to bind event

HTML

<div class='myDiv' id="div0">div0</div>
<div class='myDiv' id="div1">div1</div>
<div id="say"></div>

脚本

$("#say").append("Which div are you going to click? ");
$(".myDiv").on("click", function () {
    $("#say").append(this.id);
});

DEMO

这篇关于如何使用jQuery中的循环自动绑定多个事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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