首页 > 解决方案 > 错误:select() 不是函数 - JQuery

问题描述

我试图将输入字段内的值复制到剪贴板。获取这些值的代码工作正常,当我单击“复制”按钮时,使用 alert() 函数进行小调试,我可以在里面看到正确的值......但是当我尝试将此值设为复制到剪贴板,出现错误。我在网上看到了很多示例,但仅针对一个元素...所以,这是我的代码,它显示了正确的值,但不适用于副本。

$(document).ready(function() {
  $('div#screen_wrap').each(function() {
    var elem = $(this);
    $("#copycoords", elem).click(function() {
      var coords = $("#coords", elem).val();
      coords.select(); // This line is the error
      document.execCommand("copy", false);
      alert(coords);
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<div id="screen_wrap" class="glass">
  <div><img src="img.jpg" /></div>
  <p>Country 1</p>
  <input type="text" value="47.529016,19.050963" id="coords" />
  <input type="button" value="Copia" id="copycoords" class="btn1" />
</div>

<div id="screen_wrap" class="glass">
  <div><img src="img.jpg" /></div>
  <p>Country 2</p>
  <input type="text" value="41.662055,-0.894292" id="coords" />
  <input type="button" value="Copia" id="copycoords" class="btn1" />
</div>

<div id="screen_wrap" class="glass">
  <div><img src="img.jpg" /></div>
  <p>Country 3</p>
  <input type="text" value="38.461808,27.217074" id="coords" />
  <input type="button" value="Copia" id="copycoords" class="btn1" />

标签: jquery

解决方案


您正在select元素的值上使用该函数 - $("#coords", elem).val();,您应该只在元素本身上调用它 -$("#coords", elem).select()

顺便提一句。$("#coords", elem)是不必要的,你不应该在页面的任何地方使用相同的 id,因为 id 应该是唯一的,所以$("#coords")应该足够了


推荐阅读