2017-10-12 50 views
0

string(不Document對象),它包含HTMLbody標籤結束前添加的text/html

<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <style type="text/css" style="display:none;"> 
     <!-- P {margin-top:0;margin-bottom:0;} --> 
     </style> 
    </head> 
    <body dir="ltr"> 
     bla bla 
    </body> 
</html> 

和一些文字或其他HTML代碼,我需要先body標籤的結束前插入HTML。 以哪種方式更好地做到這一點? - 將字符串轉換爲html? - 插入文本或HTML它 - 轉換結果字符串

+0

你能告訴我們你嘗試過這麼遠嗎? –

回答

1

試試這個: -

var newHTML = "<div><p>This is New Html</p></div>"; 
    $("body").append(newHTML); 
    console.log($("body").html()); 

如果你需要連接另一個字符串中的HTML,試試這個: -

var firstString = "<div><p>This is a string</p></div>"; 
var secondString = "<p>This is another string</p>"; 
firstString += secondString; 
console.log(firstString); 

更新

function AddHtml() { 
    var firstString = "<body><div><p>This is a string</p></div></body>"; 
    var indexOfbody = firstString.indexOf("</body>"); 
    var Firsthalf = firstString.slice(0, indexOfbody); 
    var middleHalf= "<div><p>This is another string</p></div>"; 
    var LastHalf = firstString.slice(indexOfbody); 
    var FinalString = Firsthalf + middleHalf+ LastHalf; 
    console.log(FinalString); 
} 
+0

我有一個字符串,這是HTML,我需要插入到另一個字符串。與當前文檔 – Ted

+0

無關,你的意思是你必須將兩個HTML字符串合併爲一個? –

+0

是的,你是對的 – Ted

0

試試這個

var htmlString = "<p>Hello World</P>"; 
$(document.body).append(htmlString); 
0

根本就.append()

$(document).ready(function() { 
 
    $('body').append('Some content <b>with HTML!</b>'); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Existing code here<br/>