键入事件处理程序显示性能降低 [英] Keyup event handler shows slow performance

查看:58
本文介绍了键入事件处理程序显示性能降低的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的例子:

 $(document).on('keyup', '[contenteditable=true]', function (e) {
        
    let _this = $(this), text = _this.text();

    if (text.length === 1) {
        let span = $('<span>').text(text);
        _this.html(span);
    }

    console.log(_this.html());

}); 

 [contenteditable=true] {
  border: 1px solid #ccc;
} 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div> 

我的问题:如果我以正常速度在div中键入一些文本(超过1个字符),则代码可以正常工作.但是,当我尝试快速键入文本时,没有在

后面附加<span>标记.

我该如何解决?

解决方案

您可以使用input事件来代替,它在捕获用户输入时效率更高,请查看以下示例:

$(document).on('input', '[contenteditable=true]', function (e) {
    //Your logic
});

keypresskeypress作为 T.J.人群评论的 说:

$(document).on('keypress', '[contenteditable=true]', function (e) {
    //Your logic
});

希望这会有所帮助.

 $(document).on('input', '[contenteditable=true]', function (e) {
        
    let _this = $(this), text = _this.text();

    if (text.length === 1) {
        let span = $('<span>').text(text);
        _this.html(span);
    }

    console.log(_this.html());

}); 

 [contenteditable=true] {
  border: 1px solid #ccc;
} 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div> 

My example:

$(document).on('keyup', '[contenteditable=true]', function (e) {
        
    let _this = $(this), text = _this.text();

    if (text.length === 1) {
        let span = $('<span>').text(text);
        _this.html(span);
    }

    console.log(_this.html());

});

[contenteditable=true] {
  border: 1px solid #ccc;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>

My problem: If I type some text (more than 1 character) with normal speed into the div, code works fine. But, when I try to type text with fast speed, no <span> tag was appended to the div.

How can I fix that?

解决方案

You could use input event instead it's more efficient when you trach user inputs, check example below :

$(document).on('input', '[contenteditable=true]', function (e) {
    //Your logic
});

Or also keypress as T.J. Crowder comment's says :

$(document).on('keypress', '[contenteditable=true]', function (e) {
    //Your logic
});

Hope this helps.

$(document).on('input', '[contenteditable=true]', function (e) {
        
    let _this = $(this), text = _this.text();

    if (text.length === 1) {
        let span = $('<span>').text(text);
        _this.html(span);
    }

    console.log(_this.html());

});

[contenteditable=true] {
  border: 1px solid #ccc;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>

这篇关于键入事件处理程序显示性能降低的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆