最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Button click does not fire on second click - Stack Overflow

programmeradmin4浏览0评论

I have a lot of buttons with the class search_camera_btn.

When clicking on the button then it submits a form. This step works. On the other side, it should also trigger a button click event.

I wrote the event listener in a coffeescript file which sends Ajax requests, but it only works on the first click.

I put the code in this gist.

The Javascript works when the button is clicked the first time, but fails on subsequent clicks.

Actually I put a alert message in the begin of click event handler, But it only alerts at the first time. And there is no error message in my Firbug console. (I thought it is just didn't fire the click event handler.)

$(".search_camera_btn").click ->
    alert "test"

There are many buttons,no matter which button I click. It always works at the first time click. Here is my more detail source code. download

Any ideas?


I narrow down the buggy code.That is the "Ready to enter start" message only called at the first time. But there is no error showed on the Firebug Javascript console and Rails console. Should I enable some settings in the development mode ?

IW2 = get_camera_list: ->
    console.log("Start")

    ajax_req = $.ajax
      url: "update_camera_list/"
      type: "GET"
      success: (resp) -> 
        # console.log resp

    res = setTimeout (->
      ajax_req
      ), 500
    console.log("End")
    return
jQuery ->
  $(".search_camera_btn").click ->
    console.log("Ready to enter start")    
    IW2.get_camera_list()

Compiled CoffeeScript:

var IW2;

IW2 = {
  get_camera_list: function() {
    var ajax_req, res;
    console.log("Start");
    ajax_req = $.ajax({
      url: "update_camera_list/",
      type: "GET",
      success: function(resp) {}
    });
    res = setTimeout((function() {
      return ajax_req;
    }), 500);
    console.log("End");
  }
};

jQuery(function() {
  return $(".search_camera_btn").click(function() {
    console.log("Ready to enter start");
    return IW2.get_camera_list();
  });
});

I have a lot of buttons with the class search_camera_btn.

When clicking on the button then it submits a form. This step works. On the other side, it should also trigger a button click event.

I wrote the event listener in a coffeescript file which sends Ajax requests, but it only works on the first click.

I put the code in this gist.

The Javascript works when the button is clicked the first time, but fails on subsequent clicks.

Actually I put a alert message in the begin of click event handler, But it only alerts at the first time. And there is no error message in my Firbug console. (I thought it is just didn't fire the click event handler.)

$(".search_camera_btn").click ->
    alert "test"

There are many buttons,no matter which button I click. It always works at the first time click. Here is my more detail source code. download

Any ideas?


I narrow down the buggy code.That is the "Ready to enter start" message only called at the first time. But there is no error showed on the Firebug Javascript console and Rails console. Should I enable some settings in the development mode ?

IW2 = get_camera_list: ->
    console.log("Start")

    ajax_req = $.ajax
      url: "update_camera_list/"
      type: "GET"
      success: (resp) -> 
        # console.log resp

    res = setTimeout (->
      ajax_req
      ), 500
    console.log("End")
    return
jQuery ->
  $(".search_camera_btn").click ->
    console.log("Ready to enter start")    
    IW2.get_camera_list()

Compiled CoffeeScript:

var IW2;

IW2 = {
  get_camera_list: function() {
    var ajax_req, res;
    console.log("Start");
    ajax_req = $.ajax({
      url: "update_camera_list/",
      type: "GET",
      success: function(resp) {}
    });
    res = setTimeout((function() {
      return ajax_req;
    }), 500);
    console.log("End");
  }
};

jQuery(function() {
  return $(".search_camera_btn").click(function() {
    console.log("Ready to enter start");
    return IW2.get_camera_list();
  });
});
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Nov 8, 2013 at 9:34 newBikenewBike 15k29 gold badges117 silver badges204 bronze badges 9
  • 3 Can you create a jsfiddle? – Romaindr Commented Nov 8, 2013 at 9:40
  • Are you seeing any error messages in the developer window of your browser on subsequent clicks? – Paul Richter Commented Nov 11, 2013 at 3:45
  • 3 Can you elaborate more on what you mean when you say it doesn't work? How can you tell? Are you checking your server logs and you don't see a second request? Are you looking in the JavaScript console in your browser and you're not seeing a second AJAX request? If you add a console.log statement in your click function, do you see the log statement in your JavaScript console twice or no? This will help narrowing down what your problem is. – carols10cents Commented Nov 11, 2013 at 3:50
  • @carols10cents I did, but it didn't show any thing on the console. I update my post :P – newBike Commented Nov 11, 2013 at 5:07
  • 2 I think that you need to use .on as @RichPeck suggested. If your content is generated after the document has loaded, jQuery on method will still intercept the event. Try this: $(document).on('click', '.search_camera_btn', (-> alert('Got the event!') )) – Martin Commented Nov 12, 2013 at 18:00
 |  Show 4 more ments

3 Answers 3

Reset to default 13

The reason that the handler is only being fired once is because
the ".click" handler only applies to elements that are currently attached
to the DOM. If you replace the HTML after making the AJAX call, the event handlers will be lost.
You should use an event delegate instead. Try this:

jQuery(function() {
    return $("body").on("click", ".search_camera_btn", function() {
        alert("Ready to enter start");
        return IW2.get_camera_list();
     });
});

This statement basically says, if there are any elements in the DOM now, or in the future, that have a class of "search_camera_btn", and are contained within the "body" element, then fire the click handler.

I hope this helps!

Change this:

    jQuery ->
      $(".search_camera_btn").click ->
        console.log("Ready to enter start")    
        IW2.get_camera_list()

For:

jQuery ->
  $(".search_camera_btn").click ->
    console.log("Ready to enter start")    
    IW2.get_camera_list()
    return

And let me know if it helps ;)

I would make sure nothing else in your application's javascript is failing (like a simple syntax error can cause this sort of thing). Also have you tried this in different browsers? I've had a similar problem where my Ajax would work fine in Chrome but would only post once in Firefox because of some add-ons/extensions (and then I disabled them and they worked).

Also, I'm not sure if I read your gist correctly but it looks like you're specifying .click in both the jQuery of the application.js and in the btn.js.coffee, and I'm pretty sure that section in application.js should just be watching for the element's function/result and not specifying the click again.

If nothing else works, also check out ajax's .done pletion call about halfway down the page here: http://api.jquery./jQuery.ajax/ . Then show the picture list as a function after .done so you know your ajax post is always pleting before moving on to the next thing. (Ajax problems like this often tend to be server side when a call doesn't plete or there's a loop somewhere)

发布评论

评论列表(0)

  1. 暂无评论