简体   繁体   English

在span标记内套用onclick事件

[英]Apply onclick event inside a span tag

I am trying to apply an onclick event on a span tag but getting the following error. 我正在尝试在span标签上应用onclick事件,但收到以下错误。 I guess I am doing it in the right way. 我想我是用正确的方式做的。

VM409 twitter-message-73266664:892 Uncaught ReferenceError: clip is not 
defined
at HTMLSpanElement.onclick

span tag 跨度标签

<td><span id="bootstrap_css_link" class="badge  btn btn-success bootstrap_css_link" onclick="clip(this.id)" data-clipboard-target="#clipboardExample1">copy</span></td>

clip method 剪辑方法

$( document ).ready(function() {
    function clip(clip_id){
        var clipboard = new ClipboardJS(clip_id);
        clipboard.on('success', function(e) {
          setTooltip(e.trigger, 'Copied!');
          hideTooltip(e.trigger);
          //alert("hello");
        });
     } 
});

Because clip is inside a function, it's not accessible from outside it. 由于clip在函数内部,因此无法从外部进行访问。 Remove the document.ready : 删除document.ready

function clip(clip_id) {
  var clipboard = new ClipboardJS(clip_id);
  clipboard.on('success', function(e) {
    setTooltip(e.trigger, 'Copied!');
    hideTooltip(e.trigger);
  });
}

clip function is not available in global scope, since it's defined inside another function. clip函数在全局范围内不可用,因为它是在另一个函数中定义的。 You need to find the element and attach the event handler via JavaScript. 您需要找到元素并通过JavaScript附加事件处理程序。

 $(document).ready(function() { $("#bootstrap_css_link").on("click", clip); function clip(event) { console.log(event.target.id) } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <td><span id="bootstrap_css_link" class="badge btn btn-success bootstrap_css_link" data-clipboard-target="#clipboardExample1">copy</span></td> 

$( document ).ready(function() {
$('#bootstrap_css_link).click(function () {
var newArray
function clip(clip_id){
var clipboard = new ClipboardJS(clip_id);
clipboard.on('success', function(e) {
  setTooltip(e.trigger, 'Copied!');
hideTooltip(e.trigger);
//alert("hello");
});

 } 
});

});

You must define the clip function outside of $( document ).ready so you just need to define the function like this 您必须在$(document).ready之外定义clip函数,所以您只需要这样定义函数

function clip(clip_id){
    var clipboard = new ClipboardJS(clip_id);
    clipboard.on('success', function(e) {
      setTooltip(e.trigger, 'Copied!');
      hideTooltip(e.trigger);
      //alert("hello");
    });
 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM