0

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

这是我到目前为止的 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);
        }
    });
});

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

4

1 回答 1

2

它是一个<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在这里。

于 2013-08-19T19:23:47.907 回答