如何使用Turbolinks.visit(path)时防止冒泡事件

how to prevent bubbling event when use Turbolinks.visit(path)

本文关键字:事件 Turbolinks 何使用 visit path      更新时间:2023-09-26

我在自己的项目中使用 aspnetmvcturbolinks,并且我有重新加载页面Turbolinks.visit(path) 当用户在输入中添加文本时。但是,当页面更改时,我检查输入的这个keyup事件是否触发了多个,并且我添加了返回false但不起作用。

$(document).on("ready page:load", function() {
        $('input[name=keyword]').keyup(function (e) {
            alert();
            var $text = $(this).val();
            if ($text.length > 1) {
                $('html, body').animate({ scrollTop: 0 }, 600, function() {
                    Turbolinks.visit('@searchUrl' + '?keyword=' + $text);
                });
            }
            if ($text.length == 0) {
                Turbolinks.visit('@searchUrl');
            }
          return false;
        });
        $(document).on('change', 'select[name="order"]', function() {
            Turbolinks.visit('@searchUrl');
        });
        $(document).on('change', 'select[name="count"]', function() {
            Turbolinks.visit('@searchUrl');
        });
    });

什么是解决方案?谢谢

尝试使用

e.stopPropagation();

而不是

return false;

http://api.jquery.com/event.stoppropagation/

试试这个,

if(e.stopPropagation)e.stopPropagation();

else e.cancelBubble=true;//其中 e 是一个事件对象

$('input[name=keyword]').keyup(function (e) {
            alert();
            var $text = $(this).val();
            if ($text.length > 1) {
                $('html, body').animate({ scrollTop: 0 }, 600, function() {
                    Turbolinks.visit('@searchUrl' + '?keyword=' + $text);
                });
            }
            if ($text.length == 0) {
                Turbolinks.visit('@searchUrl');
                }
           if(e.stopPropagation)e.stopPropagation();
           else e.cancelBubble=true;
});