如何使用jQuery中的循环自动绑定多个事件处理程序

编程入门 行业动态 更新时间:2024-10-17 15:24:22
本文介绍了如何使用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中的循环自动绑定多个事件处理程序

本文发布于:2023-11-27 21:59:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639753.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   绑定   如何使用   事件   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!