Оптимизация функции javascript onclick, которая копирует данные из поля ввода - PullRequest
0 голосов
/ 04 марта 2019

У меня есть функция javascript, которая копирует информацию из поля ввода текста в буфер обмена, который прекрасно работает.Однако мне нужна эта функция, чтобы иметь возможность обрабатывать несколько входов или подключать несколько событий onclick к одному и тому же полю ввода.

По сути, я ищу способы оптимизировать следующее.

function h1Function() {
var copyText1 = document.getElementById("h1Input");
copyText1.select();
document.execCommand("copy");
alert("Copied the text: " + copyText1.value);
}
function h2Function() {
var copyText2 = document.getElementById("h2Input");
copyText2.select();
document.execCommand("copy");
alert("Copied the text: " + copyText2.value);
}

подключен к следующим html-полям.

<h1><a href="#" onclick="h1Function()">abcdefg123456ABCDEFG - h1</a></h1>
<input type="text" value="<div class='h1 highlight'>Din tekst her</div>" 
id="h1Input" />
<h2><a href="#" onclick="h2Function()">abcdefg123456ABCDEFG - h2</a></h2>
<input type="text" value="<div class='h2 highlight'>Din tekst her</div>" 
id="h2Input" />

Будут признательны за любые советы по оптимизации

1 Ответ

0 голосов
/ 04 марта 2019

Просто передайте идентификатор в качестве параметра функции.

function h1Function(id) {
  var copyText1 = document.getElementById(id);
  copyText1.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText1.value);
}
<h1>
  <a href="#" onclick="h1Function('input1')">abcdefg123456ABCDEFG - h1</a>
</h1>
<input type="text" id="input1" value="<div class='h1 highlight'>Din tekst her</div>" 
id="h1Input" />
<h2>
  <a href="#" onclick="h1Function('input2')">abcdefg123456ABCDEFG - h2</a>
</h2>
<input type="text" id="input2" value="<div class='h2 highlight'>Din tekst her</div>" 
id="h2Input" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...