简体   繁体   English

如果更多元素具有此类,则.click函数不适用于类

[英].click function doesn't work for class if more element have this class

This works fine: 这很好用:

$('.classname').click(function() {
  alert('');
});
<div class="classname">Click me!</div>

But this doesn't: 但这不是:

$('.classname').click(function() {
  alert('');
});
<div class="classname">Click me!</div>
<div class="classname">Click me!</div>

How can i fix this? 我怎样才能解决这个问题? Thanks for your help! 谢谢你的帮助! (The script in tags, and the .click is in a document ready function) (标签中的脚本,以及.click是文档就绪功能)

Just try this: 试试这个:

$('PARENTNODE').on('click', '.classname', function() {
  alert('');
});
<div class="classname">Click me!</div>
<div class="classname">Click me!</div>

The elements are added after your click handler is attached. 附加单击处理程序后添加元素。 By using .on() you enable it for future elements too. 通过使用.on(),您也可以为将来的元素启用它。

Replace PARENTNODE with the parent you want to delegate to (eg. body) 将PARENTNODE替换为您要委托的父级(例如正文)

Try this 尝试这个

$(document).ready(function(){
    $(document).on('click', '.classname', function() {
      alert('');
    });
});

Refer http://api.jquery.com/on/ 请参阅http://api.jquery.com/on/

You're trying to target elements that don't exist at the moment where .click is called. 您正在尝试定位在调用.click的时刻不存在的元素。

You could wrap the whole jquery code between $(function() { your code here }); 你可以将整个jquery代码包装在$(function(){your code here})之间; or move the javascript after the two <div>. 或者在两个<div>之后移动javascript。

I'm assuming that all the divs but the first one are added dynamically. 我假设所有的div,但第一个div是动态添加的。

Use an event delegated approach: 使用事件委派方法:

$(function(){
    $(document).on('click', '.classname', function() {
        alert('');
    });
}),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM