Javascript:如何修改我的代码以在主题 post 之后添加回消失的占位符

Javascript: how to modify my code to add back disappeared placeholder after topic post

我用插件手工制作了一个占位符,用于conteditable div。

显示在下面的演示中。如果用户输入一些文本然后单击 post 按钮,占位符 disappeared.I 想知道如何在 posting 之后取回占位符。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<div id="topic_content_input" contenteditable="true" autocomplete="off" spellcheck="false" data-placeholder="placeholder text" ></div>
<button id="post">Post topic</button>

<style>
#topic_content_input[data-placeholder]:not([data-div-placeholder-content]):before {
    content: attr(data-placeholder);
    float: left;
     cursor:text;
    margin-left: 2px;
    color: rgba(134,134,134,0.6);
}

#topic_content_input{
width:521px;
  padding: 10px;
  border: 1px solid orange;
}

#topic_content_input:focus{
  outline-style:solid;
  outline-color:orange;
  outline-width:0px;
  line-height:normal;
}
</style>


 <script>
 (function ($) {
    $(document).on('change keydown keypress input', '#topic_content_input[data-placeholder]', function() {
        if (this.textContent) {
            this.dataset.divPlaceholderContent = 'true';
        }
        else {
            delete(this.dataset.divPlaceholderContent);
        }
    });
    })(jQuery);
    </script>
<script>
$("#post").click(function(){
    $("#topic_content_input").text(""); 
    var obj=$("#topic_content_input");

    // $("#topic_content_input").add(obj.dataset.divPlaceholderContent);  //my attempt, not working
})

</script>

在 CSS 中,您可以输入 #topic_content_input:empty:before 而不是 #topic_content_input[data-placeholder]:not([data-div-placeholder-content]):before,只要 div 为空,它就会放在占位符中,如见于此jsfiddle

$("#topic_content_input").add(obj.dataset.divPlaceholderContent);

为什么要“.add”?

你应该使用:

obj.val(obj.dataset.divPlaceholderContent)

obj.attr('placeholder', obj.dataset.divPlaceholderContent)