2017-08-02 123 views
0

下午,我試圖創建一個簡單的HTML頁面,它有一些按鈕,當你點擊它們時,它調用一個JS將一些文本複製到剪貼板,以便它可以粘貼到其他地方( Word文檔等)。onClick按鈕最大字符長度

<body> 
    <button onclick="setClipboard('Thank you for your help.')">Greeting</button> 
    <button onclick="setClipboard('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s')">Item 2</button> 
</body> 

此呼籲:

function setClipboard(value) { 
    var tempInput = document.createElement("input"); 
    tempInput.style = "position: absolute; left: -1000px; top: -1000px"; 
    tempInput.value = value; 
    document.body.appendChild(tempInput); 
    tempInput.select(); 
    document.execCommand("copy"); 
    document.body.removeChild(tempInput); 
} 

它可以與沒有問題,但第二個它不起作用複製的第一個按鈕。如果我縮短按鈕#2中有多少單詞,它可以工作。 因此,讓我認爲它不工作,因爲那裏有多少/多少字。

任何幫助,將不勝感激。

回答

1

好像你的第二個按鈕中的文本需要quoation標記(')與一個\進行轉義,使其正常工作,就像這樣:

function setClipboard(value) { 
 
    var tempInput = document.createElement("input"); 
 
    tempInput.style = "position: absolute; left: -1000px; top: -1000px"; 
 
    tempInput.value = value; 
 
    document.body.appendChild(tempInput); 
 
    tempInput.select(); 
 
    document.execCommand("copy"); 
 
    document.body.removeChild(tempInput); 
 
    console.log(value); 
 
}
<button onclick="setClipboard('Thank you for your help.')">Greeting</button> 
 
<button onclick="setClipboard('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s')">Item 2</button>

0

這是因爲在第二個按鈕中,文本有一箇中斷字符串的單引號(')。你需要改變的開始和結束的報價在第二個按鈕,反引號(')的setClipboard,使其與雙引號上onclick和報價的工作:

<button onclick="setClipboard(`Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s`)">Item 2</button> 

反引號是明確一個的ECMAScript 6特性;它們被稱爲模板文字,並且它們允許單引號和雙引號位於字符串中。如果您的瀏覽器不支持ES6,那麼只需用反斜槓(\)轉義單引號即可。

JSFiddle

+0

在JS中,反引號不是有效的字符串分隔符,因此只會引發錯誤... – CBroe

+0

@CBroe它是ES6中的有效字符串分隔符,他們被稱爲模板文字。 –

+0

@CBroe如果您需要證明,請參閱小提琴。 –