2015-10-13 26 views
0

我可以得到的JavaScript的DIV的內容複製到剪貼板,但HTML標籤< &>出來作爲<和>而不是小於或大於符號。任何想法如何解決?鏈接到似乎不起作用的小提琴,但在本地工作。 FIDDLE的JavaScript複製HTML到剪貼板解釋< >作爲<和>

JS

function copyToClipboard(elementId) { 

    // Create a "hidden" input 
    var aux = document.createElement("input"); 

    // Assign it the value of the specified element 
    aux.setAttribute("value", document.getElementById(elementId).innerHTML); 

    // Append it to the body 
    document.body.appendChild(aux); 

    // Highlight its content 
    aux.select(); 

    // Copy the highlighted text 
    document.execCommand("copy"); 

    // Remove it from the body 
    document.body.removeChild(aux); 

} 

HTML

 <div style="display:none" > 
    <p id="p1">Content 3 blocks</p></div> 

<button onclick="copyToClipboard('p1')">Copy 1 section</button><br/> 
<button onclick="copyToClipboard('p2')">Copy 2 section</button><br/> 



    <textarea name="textarea" id="p2" cols="45" rows="5"><div class="content-section"> 
    <div class="container"> 
     <div class="row"> 
      <div class="col-md-12"> 
       <div class="page-header"> 
        <h4 class="pumpkin-txt">Content Section - 4</h4> 
       </div> 
       <p>Some text here</p> 
       <br> 
       <h5>More text here</h5> 
      </div> 
     </div> 
    </div> 
</div></textarea> 
+0

好了,不要用'.innerHTML'當你不想HTML? – Bergi

+0

我認爲這可能與它有點關係,但是如果我刪除它就會中斷。我應該用什麼來代替.innerHTML? – DivineChef

+1

對於普通的元素,試試'.textContent',在你正在尋找'.value'的textarea上。 – Bergi

回答

0

這是因爲innerHTML是否返回有效的HTML內容。 「<」在節點的值中無效,因爲它是HTML代碼。你需要替換這些自己是這樣的:

//Just an example, you need to replace all possible offending characters 
aux.setAttribute(
    "value", 
    document.getElementById(elementId).innerHTML.replace(/&lt;/g, "<") 
     .replace(/&gt;/g, ">") 
     .replace(/&quot;/g, "\"") 
); 

Working JSFiddle

相關問題