Javascript передать идентификатор типа ввода HTML в функцию - PullRequest
0 голосов
/ 29 мая 2019

Предположим, у меня есть список следующих элементов HTML с событием Javascript для копирования содержимого текста типа ввода HTML в буфер обмена:

<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>

и т. Д.

Какскопировать текст с использованием JavaScript?

Я пытаюсь настроить приведенный ниже код, но не могу понять, как передать HTML-код в код JavaScript.Я знаю, что getElementById () не является правильным в этом контексте и не должен вызываться.Но я не знаю, как перенести значение id в функцию Javascript.

<script>
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
</script>

Любая помощь будет принята с благодарностью.

Спасибо

Ответы [ 2 ]

1 голос
/ 29 мая 2019

Ошибка в том, что вы используете document.getElementById("myInput") вместо document.getElementById(myInput).

0 голосов
/ 29 мая 2019

function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById(myInput) // pass dynamic value here

console.log(copyText)
  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...