简体   繁体   English

如果仅使用javascript,如果另一个div为空,如何将innerHTML添加到div

[英]How to add innerHTML to div if another div is empty only using javascript

I have a issue about javascript. 我有一个关于javascript的问题。 I want to add innerHTML to div if it is empty. 我想将innerHTML添加到div(如果为空)。 This is my code, please help me review. 这是我的代码,请帮助我检查。 All div are the same class, not use id and only using javascript. 所有div都是同一个类,不使用id,仅使用javascript。 Thanks html: 谢谢html:

<div class="B">Test</div> <br/>
<div class="B"></div> <br/>

javascript: JavaScript的:

function test(){
    var x = document.getElementsByClassName("B");
    for (i = 0; i < x.length; i++) { 
        if (x[i].length() < 0){ 
            x[i].innerHTML = "add test";    
        }
    }
}

You need to use x[i].innerHTML.length instead of x[i].length() and it wont be less then zero at minimum it would be zero. 您需要使用x[i].innerHTML.length而不是x[i].length() ,它至少不会小于零 ,而至少是零。

Few of corrections which I made in your code 我在您的代码中所做的一些更正

  • Took length of innerHTML instead of html element div 取了innerHTML的长度而不是html元素div
  • Length is a Property so parenthesis should not be used 长度是属性,因此不应该使用括号
  • Length wont be less than zero so condition should check if length is zero. 长度不会小于零,因此条件应检查长度是否为零。
  • For being on safe side trim the innerHTML before you take length. 为了安全起见,请在修剪长度之前先修剪innerHTML。

Live Demo 现场演示

function test(){
    var x = document.getElementsByClassName("B");
    for (i = 0; i < x.length; i++) { 
        if (x[i].innerHTML.trim().length == 0){ 
            x[i].innerHTML = "add test";    
        }
    }
}

A jquery solution: 一个jQuery解决方案:

$('.B').each(function() {
   var that = $(this);
   if (that.text().length == 0) {
      that.html('add test');
   }
});

DEMO DEMO

The last two divs with class B that do not have any text will get filled with string add test B类的最后两个div没有任何文本,将使用字符串add test填充

 $('.B').each(function() { var that = $(this); if (that.text().length == 0) { that.html('add test'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="A">testA</div> <div class="B">testB</div> <div class="B"></div> <div class="B"></div> 

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

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