2014-01-13 55 views
0

我有一個隱藏的輸入字段,裏面有值,我有下面的代碼。在範圍內(<span class="telephone">&nbsp;<span>),我需要顯示隱藏字段值。我認爲我的JavaScript代碼有錯誤..如何在javascript中添加一段html代碼?在javascript中添加html blob

<input type="hidden" name="mobile" value="04323242445"/> 
    <script>  
var dateFrom =new Date(2014, 2, 3); 
var dateTo = new Date(2014, 3, 1); 
var dateCheck = Date.now(); 
if((dateCheck < dateFrom) ||(dateCheck >dateTo)){ 
    document.write(" 
//I need the below text to show up 
<div class="virginMobileError"> 
<br/> 
<p class="first">THE OFFER HAS EXPIRED FOR <span class="telephone">&nbsp;<span> AND THE CUSTOMER CAN NO LONGER REDEEM THEIR GIFT.</p> 
<br/> 
<p class="second"><span class="rep">Rep script:</span> "Unfortunately all offers have an end date and this one has ended. We can still change you to Virgin Yes Please to 
ensure that you can receive future offers from us."</p> 
</div> 
"); 
} 

+0

'''用'''打開和關閉的機會,它應該工作。 –

+0

您不應該使用'document.write'來創建HTML(某些情況除外)。 –

+0

你應該使用'document.getElementsByClassName('telephone')[0] .innerHTML =「你需要顯示的文本。」而不是'document.write(「」)'; –

回答

2

插入元素的正確方法:(注意:你不需要有id,因爲name已經足夠識別單個輸入。)

示範:http://jsfiddle.net/DerekL/hfj4T/

var dateFrom = new Date(2014, 2, 3), 
    dateTo = new Date(2014, 3, 1), 
    dateCheck = Date.now(); 

if((dateCheck < dateFrom) || (dateCheck > dateTo)){ 

//--------------------------------------- 

var hiddenEle = $("input[name=mobile]"); 

$("<div>").addClass("virginMobileError").append(
    $("<br>"), 
    $("<p>").addClass("first").html("THE OFFER HAS EXPIRED FOR <span class='telephone'>" + hiddenEle.val() +"<span> AND THE CUSTOMER CAN NO LONGER REDEEM THEIR GIFT."), 
    $("<br>"), 
    $("<p>").addClass("second").html("<span class='rep'>Rep script:</span> \"Unfortunately all offers have an end date and this one has ended. We can still change you to Virgin Yes Please to ensure that you can receive future offers from us.\"") 
).insertAfter(hiddenEle); 

//--------------------------------------- 

} 
0

你應該能夠做到多行字符串字面量在JavaScript中通過轉義一回換行符削減

<input type="hidden" name="mobile" value="04323242445"/> 
    <script>  
    var dateFrom =new Date(2014, 2, 3); 
    var dateTo = new Date(2014, 3, 1); 
    var dateCheck = Date.now(); 
    if((dateCheck < dateFrom) ||(dateCheck >dateTo)){ 
     document.write('\ 
     <div class="virginMobileError"> \ 
     <br/> \ 
     <p class="first">THE OFFER HAS EXPIRED FOR <span class="telephone">&nbsp;<span> AND THE CUSTOMER CAN NO LONGER REDEEM THEIR GIFT.</p> \ 
     <br/> \ 
     <p class="second"><span class="rep">Rep script:</span> "Unfortunately all offers have an end date and this one has ended. We can still change you to Virgin Yes Please to \ 
     ensure that you can receive future offers from us."</p> \ 
     </div>'); 
    } 
    </script> 
+0

這不起作用。雙引號內有雙引號。 – Robbert

+0

另外,'我需要顯示隱藏的字段值'。 –

+0

解決了報價轉義錯誤和內聯評論刪除 –