简体   繁体   English

JS:如果innerhtml为空,将innerhtml改成某事。 如何?

[英]JS: if innerhtml is empty, change innerhtml to something. HOW?

i'm new to js so i have a simple html element that has contenteditable="true" which i'm using as an input box.我是 js 新手,所以我有一个简单的 html 元素,它有 contenteditable="true" 我用作输入框。 i want the innerhtml to change to "CAN'T BE EMPTY" when the user has typed nothing in the input box ( " " ) and apparently it doesn't work, any tips on how i can do it?当用户在输入框(“”)中没有输入任何内容并且显然它不起作用时,我希望 innerhtml 更改为“不能为空”,关于我如何做到这一点的任何提示? this is my code (which is not working):这是我的代码(不起作用):

HTML: <p contenteditable="true" id="myparagraph">Input</p> HTML: <p contenteditable="true" id="myparagraph">Input</p>

JS: JS:

 if(document.getElementById("myparagraph").innerHTML == ""){
 document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}

i've also tried using the LENGTH property, but didn't work either:我也尝试过使用 LENGTH 属性,但也没有用:

    var plength = document.getElementById("myparagraph").innerHTML;
        var plength2 = plength.length;
if(plength2 == 0){
     document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}

It's not empty.它不是空的。 It's got a value of Input according to your HTML.根据您的 HTML,它有一个Input值。

If you want to change the value when the user edits, you need to attach an event listener :如果要在用户编辑时更改值,则需要附加事件侦听器:

 document.getElementById('myparagraph').addEventListener('input', (e) => { if (e.target.textContent.trim() === '') { e.target.textContent = 'Cannot be empty'; } })
 <p contenteditable="true" id="myparagraph">Input</p>

Note that I changed the logic from using innerHTML to using textContent because otherwise remaining empty HTML tags can prevent the warning from triggering.请注意,我将逻辑从使用innerHTML更改为使用textContent ,因为否则剩余的空 HTML 标记会阻止触发警告。 (Firefox, for example inserts a <br> when there is no content.) (例如,Firefox 在没有内容时插入<br> 。)

It would be better to display the warning anywhere than the content of the element you're trying to check.最好在任何地方显示警告而不是您要检查的元素的内容。 Add an event listener to the paragraph element.向段落元素添加事件侦听器。 In the handler get the textContent from the element, and then show/hide the warning depending on whether that text is empty.在处理程序中从元素中获取textContent ,然后根据该文本是否为空来显示/隐藏警告。

 const para = document.querySelector('#para'); const warning = document.querySelector('#warning'); para.addEventListener('input', handleInput, false); function handleInput() { const text = this.textContent; warning.textContent = text ? '' : 'Cannot be empty'; }
 #para { border: 1px solid #565656; padding: 0.5em; } #warning { color: red; }
 <p contenteditable="true" id="para">Input</p> <p id="warning"></p>

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

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