如果 <p> 没有文本,请检查 JavaScript
Check with JavaScript if <p> have no text
我需要在段落中放置一段文字,但 if 是空的。
这是我的 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>
我需要在段落中放置一段文字,但 if 是空的。
这是我的 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>