繁体   English   中英

<div> contentEditable不会立即改变,只有第二次

[英]<div> with contentEditable doesn't change immidiately, only the second time

我有2个<div> ,两个都是contentEditable,带有数据库中的值。
它的作品展示,并改变他们, 只是第二次。
例如:

  • 点击#stuff div
  • 提醒我数据库的值(例如“天气不错”)
  • 我将其更改为“新价值”
  • 在div之外单击
  • 函数提醒我#stuff div的值( 仍然 “天气还好”)
  • 在div内再次点击, 现在通知我“新价值”

这导致不得不两次进入div才能接受更改。
我手动尝试使用参数打开save.php,并直接将其保存!
我很确定这是我所缺少的基本知识,但我还不能弄清楚。

HTML:

<div id="test-container" style="border: 1px solid green;">
    <div id="editable" contentEditable="true">
        <?php echo $rst["content"]; ?>
    </div>

    <div id="stuff" contentEditable="true">
        <?php echo $rst["stuff"]; ?>
    </div>

    <button id="save">Save Changes</button>
</div>

JS函数:

var content = "";
var from = "";

/*
The code below shows the save button if anywhere in the editable div is clicked, 
and hide the button if anywhere outside the div is clicked.
*/

$("#editable, #stuff").click(function (e) {
    content = $(this).html();
    from = (this.id);

    alert(content);
    $("#save").show();
    e.stopPropagation();
});

$(document).click(function() {
    alert(content);
    $("#save").hide();

});

/*
The code below gets the data from the content variable and posts to the send.php file.
If the data is posted successfuly, the PHP file recieves the data and inserts to database, where the field is based on the form variable. 
*/

$("#save").click(function (e) {
    $.ajax({
        url: 'save.php',
        data: {
        content: content,
        from : from
        }
    });
});

我在您的代码中发现的问题是:

在键盘输入DOM更新之后,变量不变。

尝试这个:-

var content = "";
var from = "";

$("#editable, #stuff").click(function (e) {
    content = $(this).html();
    from = $(this.id);    
    console.log(content);
    e.stopPropagation();
});

$(document).click(function() {
    console.log(content);
});
$("#editable, #stuff").keyup(function(){
  content = $(this).html();
  from = $(this.id);
});

单击此处查看有效的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM