2017-08-02 75 views
0

我是javascript新手。我有一個簡單的腳本的問題。我已經搜索了很長時間的互聯網,我真的不明白我做錯了什麼。這可能只是我現在想不到的。 的問題是,當我點擊「複製1,1'-按鈕,它拷貝文本2 ...兩個不同textareas的複製按鈕

<textarea id="html" name="html">textarea 1</textarea> 
 
<input type="button" value="Copy 1" onclick="copy_to_clipboard(html);"><br><br><br> 
 
<textarea id="test" name="htmltest">textarea 2</textarea> 
 
<input type="button" value="Copy 2" onclick="copy_to_clipboard(test);"> 
 

 
<script> 
 
function copy_to_clipboard(html) 
 
{ 
 
    document.getElementById('html').select(); 
 
    document.execCommand('copy'); 
 
} 
 
function copy_to_clipboard(test) 
 
{ 
 
    document.getElementById('test').select(); 
 
    document.execCommand('copy'); 
 
} 
 
</script>

我想有一個與每個副本按鈕,兩個不同的文本區域。 ..

+0

兩個具有相同名稱的功能?只需傳遞單獨的ids作爲函數的參數並使用即可。函數的唯一目的是再次使用相同的代碼。 – Shubham

+0

您有兩個具有相同名稱的函數。 – Jer

+0

謝謝......正如我所說的。只是我現在想不到的人! :) –

回答

0

在這兩種情況下,您正在使用相同的函數名稱。請找我的更新片段

<textarea id="html" name="html">textarea 1</textarea> 
 
<input type="button" value="Copy 1" onclick="copy_to_clipboard_1(html);"><br><br><br> 
 
<textarea id="test" name="htmltest">textarea 2</textarea> 
 
<input type="button" value="Copy 2" onclick="copy_to_clipboard(test);"> 
 

 
<script> 
 
function copy_to_clipboard_1(html) 
 
{ 
 
    document.getElementById('html').select(); 
 
    document.execCommand('copy'); 
 
} 
 
function copy_to_clipboard(test) 
 
{ 
 
    document.getElementById('test').select(); 
 
    document.execCommand('copy'); 
 
} 
 
</script>

+0

爲什麼使用兩個函數。只需傳遞ID並在那裏使用。 – Shubham

+0

解決了問題,但不是一個好方法。試着只做一個。 –

1

這是因爲你已經創建了相同的名稱和參數兩種功能。你必須這樣做:

function copy_to_clipboard(ids) 
 
{ 
 
    document.getElementById(ids).select(); 
 
    document.execCommand('copy'); 
 
}
<textarea id="html" name="html">textarea 1</textarea> 
 
<input type="button" value="Copy 1" onclick="copy_to_clipboard('html');"><br><br><br> 
 
<textarea id="test" name="htmltest">textarea 2</textarea> 
 
<input type="button" value="Copy 2" onclick="copy_to_clipboard('test');">

而且在功能上經過時,調用函數時的參數,必須在配額標誌。檢入HTML代碼。

0

問題是你有兩個同名的函數。沒有必要做出兩個不同的功能。此外,請使用您在該函數中傳遞的參數,而不是單獨硬編碼id名稱。在'onclick'函數中使用反向逗號傳遞參數。

<textarea id="html" name="html">textarea 1</textarea> 
 
<input type="button" value="Copy 1" onclick="copy_to_clipboard('html');"><br><br><br> 
 
<textarea id="test" name="htmltest">textarea 2</textarea> 
 
<input type="button" value="Copy 2" onclick="copy_to_clipboard('test');"> 
 

 
<script> 
 
function copy_to_clipboard(html) 
 
{ 
 
    document.getElementById(html).select(); 
 
    document.execCommand('copy'); 
 
} 
 
</script>