document.exec()不适用于onchange

时间:2017-05-14 18:54:20

标签: javascript html

我有将文字复制到剪贴板的功能,当我使用按钮将此功能与onclick()一起使用时,它的工作正常,
如果我在onchange()上使用select,则问题就开始了。


的javascript

function copyText(text) {
  let copyfrom = document.createElement("textarea");
  document.body.appendChild(copyfrom);
  copyfrom.textContent = text
  copyfrom.select();
  document.execCommand("copy");
  copyfrom.remove()
 }


    document.getElementById('copy').onclick = function() {
  copyText("Hello world");
}


document.getElementById('idToChoose').onchange = function() {
  copyText("Hello world");}

HTML

 <div class='modal fade' id='myModal' role='dialog'>
    <div class='modal-dialog'>
        <div class='modal-content'>
            <div class='modal-header'><button type='button' class='close' data-dismiss='modal'>&times;</button>
                <h4 class='modal-title'>formats</h4>
            </div>
            <div class='modal-body'>
            <select class='form-control' id='idToChoose'>
            <option value='gradle'>gradle</option>
            <option value='ivy'>ivy</option>
            <option value='maven'>maven</option>
          </select>
                <button id='copy' type='button' class='btn btn-error' data-dismiss='modal'>copy</button>
            </div>
            <div class='modal-footer'>
                <button type='button' class='btn btn-default' data-dismiss='modal'>close</button></div>
        </div>
    </div>
</div>

3 个答案:

答案 0 :(得分:2)

document.getElementsByTagName('idToChoose')

应改为

document.querySelector('#idToChoose')

答案 1 :(得分:2)

替换

document.getElementsByTagName('idToChoose')

document.getElementsByTagName('select')

document.getElementById('idToChoose')

getElementsByTagName不适用于id值。你必须使用标签。此外,id始终是唯一的,这就是getElementById只返回一个元素的原因。

答案 2 :(得分:1)

以下代码可以自由地简化OP的HTML,专注于从下拉框选择中获取值到剪贴板。

HTML:

<select>
  <option value="*">Please choose one</option>
    <option value="gradle">gradle</option>
          <option value="ivy">ivy</option>
          <option value="maven">maven</option>
          </select>

以下JavaScript也得到了简化:

var d = document;
var val = str = "";
var s = d.getElementsByTagName("select")[0];
s.onchange = function() {
  val = s.options[s.selectedIndex].value;
  if (val == "") {
    return;
  }
    else
    {
   str = "Hello " + val;
   copyText(str);
    } 
};

function copyText( text ) {
    var textArea = d.createElement("textarea");

    d.body.appendChild( textArea );

    textArea.textContent = text;
    textArea.select();

    d.execCommand("copy");  

    textArea.remove();
}

请参阅demo

选择每个选项后,从剪贴板手动粘贴,输出:

Hello gradle
Hello ivy
Hello maven 

虽然此示例代码在GoogleChrome(版本43+)上正常运行,但显然所有主浏览器都不支持此代码。请参阅MDN说明:

copy
Copies the current selection to the clipboard. Conditions of 
having this behavior enabled vary from one browser to another,
and have evolved over time. Check the compatibility table to 
determine if you can use it in your case.