输入触发按键事件两次

发布于 2024-12-13 12:15:49 字数 762 浏览 1 评论 0原文

这个问题之前已经被问过/回答过(大部分),但是我已经尝试了三件事来阻止事件冒泡,但没有任何效果:(

return false;
e.stopPropagation();
e.preventDefault();  

返回 false 应该照顾其他两个,对吗?)

是 html:

<div class="tags-holder">
    <input type="text" class="addField" id="addField_<%= visit.id %>"  placeholder="add a new tag">
</div>

这 JS(更新已清理):

    $('.addField').show().keyup(function(event){
  event.preventDefault();
  
      if(event.keyCode == 13 || event.keyCode==9) {
    ProfilePage.createTag( this, 'nada', 'addField')
        $(this).hide().val('');

        return false;       
   }

});

我把多余的塞子留在那里,但真的不应该返回 false 来简单地杀死冒泡吗? (使用 Chrome)。

线索? keyCode=13 是“Enter”

This question has been asked/answered (mostly) before, BUT I've tried three things to stop the event from bubbling but nothing has worked:

return false;
e.stopPropagation();
e.preventDefault();  

(return false should take care of the other two, correct?)

Here's the html:

<div class="tags-holder">
    <input type="text" class="addField" id="addField_<%= visit.id %>"  placeholder="add a new tag">
</div>

And the JS (UPDATE CLEANED UP):

    $('.addField').show().keyup(function(event){
  event.preventDefault();
  
      if(event.keyCode == 13 || event.keyCode==9) {
    ProfilePage.createTag( this, 'nada', 'addField')
        $(this).hide().val('');

        return false;       
   }

});

I left the redundant stoppers in there but really shouldn't return false simply kill the bubbling? (using Chrome).

Clue? keyCode=13 is "Enter"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

过期情话 2024-12-20 12:15:49

哇。你的帮助非常大,帮助我思考了这个问题。

但这个解决方案感觉有点像是逃避现实。有效,但这种情况从一开始就不应该存在。

这是我在此处的评论中找到的:
http://yuji.wordpress.com/2010/ 02/22/jquery-click-event-fires-twice/

    $('.plus').unbind('click').bind('click',function(e){    
console.log('clicked')
    var id=$(this).attr('plus_id');
    var field=$('<input type="text">').attr({'placeholder':'add a new tag','id': 'addField_' + id, 'visit_id':id});
    field.focus();
    field.show().keydown(function(event){
        event.stopImmediatePropagation();
        if(event.keyCode == 13 || event.keyCode==9) {
            console.log(event)
            ProfilePage.createTag( field, 'nada', 'addField')
            field.hide().val('');
            return false;       
        }
    }).click(function(e){
        return false;
    })
    ;
$(this).append(field);
return false;       
   });

Wow. Your help was great and helped me think it through.

BUT the solution feels a bit like a cop-out; effective, but the condition should never be there in the first place.

Here it is, which I found in the comments from here:
http://yuji.wordpress.com/2010/02/22/jquery-click-event-fires-twice/

    $('.plus').unbind('click').bind('click',function(e){    
console.log('clicked')
    var id=$(this).attr('plus_id');
    var field=$('<input type="text">').attr({'placeholder':'add a new tag','id': 'addField_' + id, 'visit_id':id});
    field.focus();
    field.show().keydown(function(event){
        event.stopImmediatePropagation();
        if(event.keyCode == 13 || event.keyCode==9) {
            console.log(event)
            ProfilePage.createTag( field, 'nada', 'addField')
            field.hide().val('');
            return false;       
        }
    }).click(function(e){
        return false;
    })
    ;
$(this).append(field);
return false;       
   });
<逆流佳人身旁 2024-12-20 12:15:49

我遇到了同样的问题,我使用了上面的方法,它对我有用。

$(document).unbind('keypress').bind('keypress', function (e) {
   // some logic here
});

I had same issue and I used above method and it work for me.

$(document).unbind('keypress').bind('keypress', function (e) {
   // some logic here
});
黑凤梨 2024-12-20 12:15:49

尝试先解除绑定事件然后绑定它,请参考下面的代码:

$('.addField').show().unbind('keyup').keyup(function(event){
 event.preventDefault();

  if(event.keyCode == 13 || event.keyCode==9) {
ProfilePage.createTag( this, 'nada', 'addField')
    $(this).hide().val('');

    return false;       
}

解释是 这里,我在我的新博客上写了一篇关于此的文章。

Try unbinding the event first then bind it, refer below code:

$('.addField').show().unbind('keyup').keyup(function(event){
 event.preventDefault();

  if(event.keyCode == 13 || event.keyCode==9) {
ProfilePage.createTag( this, 'nada', 'addField')
    $(this).hide().val('');

    return false;       
}

An explanation is here, i had written a post about this on my new blog.

沧桑㈠ 2024-12-20 12:15:49

希望这能解决您的问题。
不要使用 event.preventDefault(),而是使用下面显示的这两个。
如果使用 Microsoft 浏览器
event.cancelBubble = true;
如果是 W3C 模型浏览器使用
event.stopPropagation();

并且不要使用 Keyup 事件,而是使用 keypress 事件,因为在按键期间,输入将被发送到输入字段,因此您不想出现的任何输入都会出现在该字段上。这样就会触发回车按钮事件。

使用 event.returnValue = false 而不是返回 false。

Hope this will solve your problem.
Instead of using event.preventDefault() use these two shown below.
In case of Microsoft browsers use
event.cancelBubble = true;
In case of W3C model browsers use
event.stopPropagation();

And Instead of Keyup event kindly use the keypress event, because during keypress itself the input will be sent to input field so whatever inputs you don't want to appear will appear on the field. So the enter button event will be triggered.

Instead of return false use event.returnValue = false.

上课铃就是安魂曲 2024-12-20 12:15:49

的所有实例

$(field).functionCall() 

尝试更改to

field.functionCall() 

,因为 field 已经是一个 jQuery 对象。

好的,现在我们已经确定这不是错误。我在 Firefox 7 和 Chrome 15 中进行了测试,发现 if 语句中的代码块仅在按下 Enter 键时触发一次。尝试检查以确保 createTag() 函数内的某些操作不会执行两次。

Try changing all the instances of

$(field).functionCall() 

to

field.functionCall() 

since field is already a jQuery object.

Ok now we've established that this wasn't the error. I tested in Firefox 7 and Chrome 15 and saw that the code block in the if statement is only fired once when enter is pressed. Try checking to make sure that something inside the createTag() function isn't doing something twice.

挖个坑埋了你 2024-12-20 12:15:49

你认为什么是在事件冒泡时捕捉事件。我只在这个测试页上触发了一次。

<!DOCTYPE html>
<html>
  <head>
    <title>Scratch</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.setOnLoadCallback(function (){
        $('input[type="text"]').keyup(function (){
          console.debug('keyup');
        });
      });
      google.load('jquery', '1.6.4');
    </script>
  </head>
  <body>

    <div class="something">
      <input type="text" />
    </div>
  </body>
</html>

也许这是你的选择器。它是否嵌套在另一个 .addTag 中?当我更改 jQuery 选择器并使 div 和 input 成为同一类时,我开始触发两个事件。像这样:

$('.thing').show().keyup(...);

...并且...

<div class="thing">
    <input class="thing" type="text" />
</div>

What do you think is catching the event when it bubbles. I only get one firing with this test page.

<!DOCTYPE html>
<html>
  <head>
    <title>Scratch</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.setOnLoadCallback(function (){
        $('input[type="text"]').keyup(function (){
          console.debug('keyup');
        });
      });
      google.load('jquery', '1.6.4');
    </script>
  </head>
  <body>

    <div class="something">
      <input type="text" />
    </div>
  </body>
</html>

Maybe it's your selector. Is it nested inside another .addTag? When I change the jQuery selector and also make the div and input the same class I start to get two events firing. Like this:

$('.thing').show().keyup(...);

...and...

<div class="thing">
    <input class="thing" type="text" />
</div>
幸福不弃 2024-12-20 12:15:49

这是一个总是让我发疯的问题,但我认为这是解决方案
只需返回 false,如果返回 true,它会随机重复自己,所以我猜测它一定有一个侦听器来侦听真实的响应。

简答
添加返回假;

$("#register-form #first_name").keyup(function(event) {
console.log('hello world');
return false;

});

在最初的问题中,如果仔细查看代码,似乎 return false 被写得太早了一行。

This is a problem which always drives me insane but i think this is the solution
simply return false, if you return true it repeats it self randomly so im guessing it must have a listener which listens out for true responses.

Short Answer
Add return false;

$("#register-form #first_name").keyup(function(event) {
console.log('hello world');
return false;

});

in the original question if you look at the code closely is seems the return false was written one line too early.

め七分饶幸 2024-12-20 12:15:49

我在使用 Angular 11 EventEmitters 时遇到了这个问题。我通过创建事件发射器的新实例来解决这个问题
事件被触发。

@Output() keypress = new EventEmitter();
onKeyPress(event) {
   this.keypress = new EventEmitter();
   this.keypress.emit(event);
 }

I had this issue using Angular 11 EventEmitters. I solved it by creating a new instance of my event emitter whenever the
event is triggered.

@Output() keypress = new EventEmitter();
onKeyPress(event) {
   this.keypress = new EventEmitter();
   this.keypress.emit(event);
 }
风尘浪孓 2024-12-20 12:15:49

我也经历过同样的事情,这个结构对我有用:

const onKeyPress = (e: React.KeyboardEvent): void => {
    if (onSubmit && e.key.toLowerCase() === 'enter') {
      onSubmit();

      e.stopPropagation();
      e.preventDefault();
    }
};

I passed through the same and this structure worked for me:

const onKeyPress = (e: React.KeyboardEvent): void => {
    if (onSubmit && e.key.toLowerCase() === 'enter') {
      onSubmit();

      e.stopPropagation();
      e.preventDefault();
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文