【问题标题】:max limit set in paragraph tag with contentEditable true在 contentEditable 为 true 的段落标签中设置的最大限制
【发布时间】:2020-04-10 07:34:14
【问题描述】:

我有一个可编辑的段落标签,我想对其设置最大限制。在最大限制之后,字符不应该是类型。我试过了,但没用。

<p id="business_title" contentEditable="true" onkeypress="limitMessage(this.id,event);">hhhhh</p>

jquery 是:

function limitMessage(id,e){
        var tval = $('#'+id).val(),
            tlength = tval.length,
            set = 10,
            remain = parseInt(set - tlength);
        if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
            $('#'+id).val((tval).substring(0, tlength - 1))
        }
    }

【问题讨论】:

    标签: javascript php jquery html css


    【解决方案1】:

    您忘记了 jQuery CDN,并且您使用的是 p 而不是 input,那么您需要使用 html() 而不是 val(),因为 p 元素不期望值。

    而且你不需要写$(this).val((tval).substring(0, tlength - 1)),因为它会回到句子的开头,所以只需使用preventDefault()来停止写。

    试试这个:

    function limitMessage(id, e) {
      var tval = $('#' + id).html(),
        tlength = tval.length,
        set = 10,
        remain = parseInt(set - tlength);
      if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        e.preventDefault();
      }
    }
    body {
      background-color: white;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <p id="business_title" contentEditable="true" onkeypress="limitMessage(this.id,event);">hello</p>

    【讨论】:

    • @Vinod 好的,我想我找到了,我刚刚更新了我的答案,你可以试试吗?
    • Uncaught ReferenceError: e is not defined at HTMLHeadingElement.onkeypress
    【解决方案2】:

    请试试这个。

    function limitMessage(id, e) {
      var tval = $('#' + id).html(),
        tlength = tval.length,
        set = 10,
        remain = parseInt(set - tlength);
      if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        $('#' + id).html((tval).substring(0, set + 1));
        e.preventDefault();
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p id="business_title" contentEditable="true" onkeypress="limitMessage(this.id,event);">hhhhh</p>

    说明

    1. 您使用的是 .val 而不是 .html。
    2. 当您向后插入字符串时,光标被重置为字符串开头并添加了新字符并修剪了字符串结尾的字符。为了解决这个问题,我添加了 e.preventDefault 以阻止添加字符。

    【讨论】:

    • 请在您的回答中添加更多解释,以帮助其他人了解您是如何解决问题的。
    • Uncaught ReferenceError: e is not defined at HTMLHeadingElement.onkeypress
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多