Mr.*_* Jo 2 html javascript jquery
我的 contenteditable div 有问题。我目前正在尝试检测 div 元素中的任何变化。到目前为止,这效果很好。但是当我通过 jQuery 更改内容时它失败了:
jQuery(document).ready(function($) {
let input = $("#input");
input.on("input", function() {
console.log($(this).html().length);
});
$("button").click(function() {
input.html(input.html() + `<span class="emoji"></span>`);
});
});Run Code Online (Sandbox Code Playgroud)
div {
border: 1px solid #aaaaaa;
padding: 8px;
border-radius: 12px;
margin-bottom: 20px;
}
[contenteditable=true]:empty:before {
content: attr(placeholder);
display: block;
color: #aaaaaa;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="input" placeholder="Schreib eine Nachricht..." contenteditable="true" spellcheck="true"></div>
<button>Add element to contenteditable div</button>Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?我可以在我的点击事件中执行此检查,但我需要添加很多,所以我不想每次都这样做。在这种情况下,我认为最好在一个输入检查函数中完成此操作。
在这种情况下,您需要触发您正在收听的事件:
jQuery(document).ready(function($) {
let input = $("#input");
input.on("input", function() {
console.log($(this).html().length);
// Contenteditable adds a <br> when empty.
// Solutions on SO appear not to work
if (!$(this).text()) {
console.log('cleared editable');
input.html('');
}
});
$("button").click(function() {
input.html(input.html() + `<span class="emoji"></span>`);
input.trigger('input');
});
});Run Code Online (Sandbox Code Playgroud)
[contenteditable=true] {
border: 1px solid #aaaaaa;
padding: 8px;
border-radius: 12px;
margin-bottom: 20px;
}
[contenteditable=true]:empty:before {
content: attr(placeholder);
display: block;
color: #aaaaaa;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="input" placeholder="Schreib eine Nachricht..." contenteditable="true" spellcheck="true"></div>
<button>Add element to contenteditable div</button>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
785 次 |
| 最近记录: |