内容上的启用/禁用按钮可编辑按键

Enable/disable button on contentEditable keyup

本文关键字:按钮 编辑按 启用      更新时间:2023-09-26

我的网站上有几个div使用HTML5 contentEditable属性。目标是让用户能够开始编写日记条目,并将保存按钮从禁用更改为启用。

这是我目前拥有的HTML:

<div id="entry-create-partial">
  <div id="title-create-partial" name="title" contenteditable="true" data-placeholder='Title it' style="color:black"></div>
  <div id="content-create-partial" name="content" contenteditable="true" style="color:gray">Write anything</div>
  <button type="button" id="create-entry" class="btn" disabled="true">Save</button>
</div>

这是jQuery:

$(document).ready(function(){
    $('#title-create-partial').keyup(function(){
        if ($(this).value == '') {
            $('#create-entry').attr('disabled', 'disabled');
        } else {
            $('#create-entry').attr('disabled', false);
        }
    });
});

虽然这确实有效,但它只检查第一个按键;如果用户退格并删除他们键入的所有内容,则按钮不会再次禁用自己。有人知道为什么吗?

这是一个<div>元素,而不是<input>,所以请使用text()而不是val()(请确保进行修剪,以免在空白处启用)。也可以使用prop()来设置属性,而不是使用attr()

$('#title-create-partial').keyup(function(){
    if ($.trim($(this).text()) === '') {
        $('#create-entry').prop('disabled', true);
    } else {
        $('#create-entry').prop('disabled', false);
    }
});

jsFiddle在这里