2016-07-27 49 views
-1

我不知道JavaScript,但我想做一些我不知道如何。在此代码中,这些行不断重复:Javascript |如果句子

if (jsonLength==0) 
{ 

    html+='<div class="desc"> <div class="thumb"> <img class="img-circle" src="" width="35px" height="35px" align=""> </div> <div class="details"><p style="padding-left: 10px;"><a href="#"></a><br/>Sê o primeiro a escrever no chat!</p></div> </div>'; 
} 

如何阻止它们重复?这里的完整代码

var lastTimeID = 0; 

$(document).ready(function() { 
    $('#btnSend').click(function(){ 
     sendChatText(); 
     $('#chatInput').val(""); 
    }); 
    startChat(); 
}); 

function startChat(){ 
    setInterval(function(){ getChatText(); }, 700); 

} 

function getChatText(){ 
    $.ajax({ 
     type: "GET", 
     url: "/refresh.php?lastTimeID="+lastTimeID 
    }).done(function(data) 
    { 
     var jsonData = JSON.parse(data); 
     var jsonLength = jsonData.results.length; 
     var html = ''; 

     for (var i = 0; i < jsonLength; i++) { 
      var result = jsonData.results[i]; 
      html += '<div class="desc"> <div class="thumb"> <img class="img-circle" src="' + result.picture +'" width="35px" height="35px" align=""> </div> <div class="details"><p style="padding-left: 10px;"><a href="#">' + result.user_name +'</a><br/>'+result.chattext+ '</p></div> </div>'; 
      lastTimeID = result.id; 
     } 
     if (jsonLength==0) 
{ 

    html+='<div class="desc"> <div class="thumb"> <img class="img-circle" src="" width="35px" height="35px" align=""> </div> <div class="details"><p style="padding-left: 10px;"><a href="#"></a><br/>Sê o primeiro a escrever no chat!</p></div> </div>'; 
} 
     $('#view_ajax').append(html); 

    }); 
} 

function sendChatText(){ 
    var chatInput = $('#chatInput').val(); 
    if(chatInput != ""){ 
     $.ajax({ 
      type: "GET", 
      url: "/submit.php?chattext=" + encodeURIComponent(chatInput) 
     }); 
    } 
} 

它有一些PHP的部分,但我不认为他们是有用的这个问题

在此先感谢

回答

1

将低于您var html = '';

if (jsonLength==0) 
{ 
    html+='<p>Nothing!</p>'; 
} 
+0

它让垃圾邮件的div,我该如何解决这个问题 – getl0st

1
这一权利

这应该可以帮助你在JavaScript中。

//Put the following if statment inside the done function 
if (data != null) { 
    document.getElementById('yourDivID').insertAdjacentHTML('afterend','<p> Nothing! </p>'); 
} 

这是你会怎么做jQuery的。

//Put the following if statment inside the done function 

if (data != null) { 
    $('#yourDivID').append('<p> Nothing! </p>'); 
}