jQuery Class selector not working

纵饮孤独 提交于 2019-11-30 06:48:05

Try using the live() command:

$(".bar").live("click", function(){ alert(); });

Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.

More details, here

Edgar Villegas Alvarado

You surely missed $(document).ready(). Your code should be:

  $(document).ready(function(){
      $('.bar').click(function()
      {
        alert("CLICKED");
      });
    });

Hope this helps. Cheers

.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:

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

Thanks to @Blazemonger for the fix.

  1. Make sure you have included JQuery Library properly.
  2. Make sure your script has written between $(document).ready() in short $(function(){ });

Demo : http://jsfiddle.net/W9PXG/1/

<div id="foo">
  <a class='bar' href='#'>Next</a>
</div>

$(function(){
$('a.bar').click(function()
  {
    alert("CLICKED");
});
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!