如果<;p>;没有文本


Check with JavaScript if <p> have no text

我需要在段落中放入一个文本,但前提是它为空。

这是我的JavaScript函数,不起作用:

function myFunction(id,name) {
var var1=document.getElementById(id);
if(var1.text==null){
document.getElementById(id).innerHTML = name;
}}

我有这两段

<p id="1"></p>
<p id="2">Im not Empty</p>

事实上,使用前面的函数,两个段落都会获取文本,但我只需要将文本放在其中的第一个段落中。

这是php的一部分,这个部分工作。问题就出在JavaScript函数上。

<?php
$idVar=1;
$strVar="I was empty";
while($idVar<=2){
echo "<button onclick='myFunction(".json_encode($idVar).",".json_encode($strVar).")' type='button' id='botones'></button>";
$idVar++;
}
?>

请帮忙,谢谢。

使用textContent并使用''而不是null 检查是否为空

function myFunction(id,name) {
var var1=document.getElementById(id);
if(var1.textContent==''){
document.getElementById(id).innerHTML = name;
}}

function myFunction(id, name) {
  var var1 = document.getElementById(id);
  console.log(var1.textContent);
  if (var1.textContent == '') {
    document.getElementById(id).innerHTML = name;
  }
}
myFunction(1, 'test');
<p id="1"></p>
<p id="2">Im not Empty</p>