javascript .preventDefault() 不起作用。('input', function{})

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32298064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:04:57  来源:igfitidea点击:

.preventDefault() not working in on.('input', function{})

javascriptjqueryhtmldom-eventsevent-propagation

提问by Da Artagnan

I would like to limit number of chars in my editable div to 10. After user reach the limit I would like to use .preventDefault()method to protect the div from additional chars. Can You help me out, please?

我想将我的可编辑 div 中的字符数限制为 10。在用户达到限制后,我想使用.preventDefault()方法来保护 div 免受额外字符的影响。请你帮帮我好吗?

JSFiddle https://jsfiddle.net/7x2dfgx6/1/

JSFiddle https://jsfiddle.net/7x2dfgx6/1/

HTML

HTML

<div class="profileInfo" id="About" style="border:solid;" contenteditable="true">OOOOO</div>

JQuery

查询

    jQuery(document).ready(function($){

    const limit = 10;
    rem = limit - $('#About').text().length;
    $("#counter").append("You have <strong>" + rem + "</strong> chars left.");
    $("#About").on('input', function(event) {
        var char = $('#About').text().length;
        rem = limit - char;
        $("#counter").html("You have <strong>" + rem + "</strong> chars left.");
        if(char>limit)
        {
            event.preventDefault();
            //TODO
        }
    });
});

回答by Artur Filipiak

To answer your main question:
.preventDefault()cancel behavior of the events that are cancelable. inputevent is not .

要回答你的主要问题:
.preventDefault()取消是事件的行为取消input事件不是。

To check whether an eventis cancelable, try: console.log(event.cancelable);.
For inputit will say "false"

要检查是否event可以取消,尝试:console.log(event.cancelable);
因为input它会说“假”



You may want something like this (untested):

你可能想要这样的东西(未经测试):

const limit = 10;
var rem = limit - $('#About').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#About").on('input', function(event) {
    var char = $(this).text().length;
    rem = limit - char;
    if(rem <= 0){
        $(this).text($(this).text().slice(0, limit));
    }
    $("#counter").html("You have <strong>" + rem + "</strong> chars left.");
});


EDIT

编辑

JSFiddle demo
Since it's contentEditable, I had to use an additional code (from thisanswer) to set a caret at the end of the input.

JSFiddle 演示
因为它是contentEditable,所以我不得不使用额外的代码(来自这个答案)在输入的末尾设置一个插入符号。

回答by Nageshwar Reddy

use keydowninstead of input

使用keydown代替input

jQuery(document).ready(function($){

    const limit = 10;
    rem = limit - $('#About').text().length;
    $("#counter").append("You have <strong>" + rem + "</strong> chars left.");
    $("#About").on('keypress', function(event) {
        var char = $('#About').text().length;
        if(char>limit)
        {
            return false;
            //or
            event.preventDefault();
            //TODO
        }
        rem = limit - char;
        $("#counter").html("You have <strong>" + rem + "</strong> chars left.");

    });

});

DEMO

演示

回答by grantk

Try changing the value of the contenEditable attribute. Also I set the check for the limit to >=

尝试更改 contenEditable 属性的值。此外,我将限制检查设置为 >=

jQuery(document).ready(function($){

    const limit = 10;
    rem = limit - $('#About').text().length;
    $("#counter").append("You have <strong>" + rem + "</strong> chars left.");
    $("#About").on('input', function(event) {
        var char = $('#About').text().length;
        rem = limit - char;
        event.preventDefault();
        if(char>=limit)
        {
            $('#About').attr('contenteditable','False');
            //TODO
        }
        $("#counter").html("You have <strong>" + rem + "</strong> chars left.");
    });

});

回答by moto

Here is one way to limit the characters in an input. Works with paste and typing.

这是限制输入中字符的一种方法。适用于粘贴和打字。

/**
 * Limit an inputs number of characters
 * @param {event} e - event of the input the user is typing into
 * @param {number} limit - number of characters to limit to 
 */
function limitInputCharacters(e, limit){
  if(!e){
    return;
  }
  var inputText = e.target.value;
  var charsLeft = limit - inputText.length;
  if (charsLeft >= 0) {
    // do something, or nothing
  } else if (charsLeft < 0) {
    e.target.value = inputText.slice(0, limit)
  }
}

document.addEventListener("DOMContentLoaded", function() {
  const aboutTextArea = document.getElementById('input-about');
  aboutTextArea.addEventListener("input", function(e) {
    limitInputCharacters(e, 300)
  })
})

回答by PN GH

el.addEventListener('input', function(event) {

 if ( this.innerHTML.length >300  && event.keyCode != 8) {

   document.execCommand("undo");  

 }

 });