Jquery添加点击功能到几个跨度具有相同的类 [英] Jquery adding click function to several spans with the same Class

查看:206
本文介绍了Jquery添加点击功能到几个跨度具有相同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jquery使用他们的类添加一个 .click()函数到几个动态生成的跨度。我想要的基本上是:

I'm trying to use jquery to add a .click() function to several dynamically generated spans using their class. What I'm trying is essentially:

$(".spanClass").click(function () {});

我也尝试过:

$(".spanClass").on("click", function () {});

现在,这一切都可以实现。我的问题是 .click()只被分配给这个类的第一个span。每一个其他跨度与这个类绝对没有什么,当我点击它。显然,我需要类的每一个span有 .click()

Now, this all works, to an extent. My issue is that the .click() only gets assigned to the first span with this class. Every other span with this class does absolutely nothing when I click it. Obviously, I need every span with the class to have the .click().

请注意,我的跨度包含在表的单元格内。每个span在不同的单元格中,每个包含一个span的表行只有一个单元格。

It may be important to note that my spans are contained inside cells of a table. Each span is in a different cell, and there is only one cell per table row that contains a span.

任何帮助都非常感谢。

JSFiddle我的工作。 JSFiddle链接

JSFiddle of what I'm working with. JSFiddle link

编辑注意:最初这个问题涉及使用ID而不是类。

Edit note: Originally this question involved using an ID instead of a class. People noted I should use class instead, and should edit the question if that didn't work.

编辑2:添加关于表格的信息。

Edit 2: Added info about tables.

最后编辑:选择最佳解决方案。如果你遇到这个问题,最好的答案是功能。我的问题是我的.on(click)函数本身内的脚本问题。

Final edit: Best solution chosen. If you come across this issue, best answer is functioning. My issue was a scripting issue inside my .on("click") function itself.

推荐答案

c $ c> class 而不是 id

You need to use a class instead of an id.

id 在整个网页中应该是唯一的:

The id should be unique in the entire page:


ID在文档中必须是唯一的,通常用于使用getElementById检索元素。

The ID must be unique in a document, and is often used to retrieve the element using getElementById.

尝试分配点击事件,它将仅在 id = 时第一次发生 spanId

Because of this, trying to assign the click event to it will fire only on the first occurence of the span with id = spanId

请参见下面的示例,并使用 .on(click,function())代替 .click()

See example below, and use .on("click", function()) instead of .click()

$(".yourspanclass").on("click", function(){
    // do what you need on click 
});

查看工作示例 此处

see a working example HERE

这篇关于Jquery添加点击功能到几个跨度具有相同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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