将字符串传递到事件监听器函数

时间:2019-10-07 10:41:41

标签: javascript dom-events

我试图在单击按钮时将一些文本复制到剪贴板。当前,当我有一个单独的函数来复制要复制的HTML的不同部分时,它可以工作,但是当我为两个参数都写一个函数时,它不起作用。

我有2个看起来像这样的功能

function copyStringToClipboardA () {
  // Create new element
  var el = document.createElement('input');
  // Set value (string to be copied)
  el.value = document.getElementById("trackEvent").value;
  // Set non-editable to avoid focus and move outside of view
  el.setAttribute('readonly', '');
  el.style = {position: 'absolute', left: '-9999px'};
  document.body.appendChild(el);
  // Select text inside element
  el.select();
  // Copy text to clipboard
  document.execCommand('copy');
  // Remove temporary element
  document.body.removeChild(el);
}

function copyStringToClipboardB() {
  // Create new element
  var el = document.createElement('input');
  // Set value (string to be copied)
  el.value = document.getElementById("identifyEvent").value;
  // Set non-editable to avoid focus and move outside of view
  el.setAttribute('readonly', '');
  el.style = {position: 'absolute', left: '-9999px'};
  document.body.appendChild(el);
  // Select text inside element
  el.select();
  // Copy text to clipboard
  document.execCommand('copy');
  // Remove temporary element
  document.body.removeChild(el);
}

这两个功能唯一不同的是el.value

我会在如下所示的单击按钮上调用这两个函数:

document.addEventListener("DOMContentLoaded", function(event){
//Event Examples
    var b = document.getElementById('trackCopy');
    var c = document.getElementById('identifyCopy');

    b.addEventListener('click', copyStringToClipboardA, false);
    c.addEventListener('click', copyStringToClipboardB, false)
});

我正在尝试编写1个将字符串作为参数的函数,而不是编写2个函数。 我尝试编写以下函数,该函数将字符串作为参数:

function copyStringToClipboard(myInput) {
  // Create new element
  var el = document.createElement('input');
  // Set value (string to be copied)
  el.value = document.getElementById(myInput).value;
  // Set non-editable to avoid focus and move outside of view
  el.setAttribute('readonly', '');
  el.style = {position: 'absolute', left: '-9999px'};
  document.body.appendChild(el);
  // Select text inside element
  el.select();
  // Copy text to clipboard
  document.execCommand('copy');
  // Remove temporary element
  document.body.removeChild(el);
}

然后按如下方式单击它:

document.addEventListener("DOMContentLoaded", function(event){
//Event Examples
    var b = document.getElementById('trackCopy');
    var c = document.getElementById('identifyCopy');

    b.addEventListener('click', copyStringToClipboard("trackEvent"), false);
    c.addEventListener('click', copyStringToClipboard("identifyEvent"), false)    
});

此实现的问题在于,每次复制第二个identifyEvent

我要实现的行为是将选定的文本复制到剪贴板中。

0 个答案:

没有答案