首页 > 解决方案 > 我无法在 javaScript 中选择和复制 onclick 事件“span 元素”

问题描述

select()函数正在使用输入标签,但不适用于跨度标签。如何解决?

<span id="selector">paragraph<span>
<script>
  document.getElementById("selector").addEventListner("click", 
  myFunction);

function myFunction(){
  var selectItem = document.getElementById("selector");
  selectItem.select();
  document.execCommand("copy");

  };
 </script>

标签: javascripthtml

解决方案


可能,原因是正确使用select()函数不包括span标签,正如MDN网站所说:

“HTMLInputElement.select() 方法选择一个元素或包含文本字段的元素中的所有文本。”

MDN 参考

在您的代码中正确使用如下:

<span id="selector1">paragraph<span>
	<input id="to_select" type="text" name="text1" value="paragraph">
	<input id="selector" type="button" value="Selector">
	<script>
	  document.getElementById("selector").addEventListener("click", 
	  myFunction);

	function myFunction(){
	  var selectItem = document.getElementById("to_select");
	  selectItem.select();
	  document.execCommand("copy");

	  };
</script>

此外,@Jason Aller 的评论是正确的:“addEventListner 拼写不正确”


推荐阅读