weixin_33676492 2016-02-01 15:15 采纳率: 0%
浏览 74

jQuery事件触发两次

I have a text area that's meant to mimic the effects of a chat box I.E. when I press enter it makes an AJAX request. The problem is that the request is made twice:

$('html').on('keyup', '#message-text', function(e){
  if(e.which == 13 && !e.shiftKey){
    e.preventDefault();
    e.stopPropagation();
    $.ajax({...},
      success: function(){
        console.log("*****POST****");
      },
      error: function(){
        console.log("failure");
      }
    })
  }
});

Whenever I press enter, the AJAX request is made successfully twice and in the console ****POST**** is logged twice when the button is pressed once. The source for one log is from messages.js:43 (my file) and a file I'm not familiar with VM3339:43. What's the issue?

  • 写回答

1条回答 默认 最新

  • weixin_33739646 2016-02-01 15:50
    关注

    If you use .stopImmediatePropagation() instead of .stopPropagation(), you'll kill the event before any redundant handlers are invoked.

    Now, of course, if that works, then it means that your setup code is running twice, perhaps because the script file is inadvertently imported in two <script> tags. There's nothing bad about .stopImmediatePropagation(), but it'd probably be good to get rid of whatever's causing the code to run twice.

    评论

报告相同问题?