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.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么