Jquery adding click function to several spans with the same Class

岁酱吖の 提交于 2019-12-25 16:52:25

问题


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

I have also tried:

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

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().

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.

Any help is greatly appreciated.

JSFiddle of what I'm working with. JSFiddle link

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.

Edit 2: Added info about tables.

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.


回答1:


You need to use a class instead of an id.

The id should be unique in the entire page:

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

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

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



来源:https://stackoverflow.com/questions/24070244/jquery-adding-click-function-to-several-spans-with-the-same-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!