【问题标题】:Onclick function is not defined [duplicate]Onclick 功能未定义[重复]
【发布时间】:2018-11-26 08:52:20
【问题描述】:

我想用onclick="" 调用这个相当简单的函数。不管我做什么,我都会收到错误Function is not defined

html:

<a href="#" onclick="shareURL(); return false;" data-share="https://www.facebook.com/sharer/sharer.php?u=" href="#">Share on Facebook</a>

js:

function shareURL() {
  var $url = window.location.href;
  var $src = $(this).data("share");
  $url = encodeURI($url);
  if ($src) {
    window.location.href = $url + $src;
  }
}

函数驻留在准备好的文档中,就像在这个Fiddle中一样。

【问题讨论】:

  • 这样试一下,就可以了。jsfiddle.net/3vwc0sp2/8
  • 你添加jquery了吗?
  • 在你的小提琴中,你有 on ready 包装器,更改为 no-wrapper - head
  • 阅读scope。您的shareURL 函数仅在document.ready 范围内定义 - 在该范围之外不可见,onclick= 不可见。如果您按照建议使用 jquery 来连接事件,那么这也会发生在 doc.ready 内部,因此会在同一范围内找到函数。

标签: jquery


【解决方案1】:

您必须将您的 shareURL 方法放在 $(document).ready{function()} 之外,请考虑以下示例以了解更多详细信息。

下面的示例工作正常,因为我已将 shareURL 方法放在 document.ready 方法

function shareURL() {
  var $url = window.location.href;
  var $src = $(this).data("share");
  $url = encodeURI($url);
  console.log("method called!");
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="shareURL(); return false;" data-share="https://www.facebook.com/sharer/sharer.php?u=" href="#">Share on Facebook</a>

以下内容将不起作用,因为共享网址的范围仅限于 document.ready 方法

$(document).ready(function(){
  function shareURL() {
    //this will not work as scope of the function is limited to document
    var $url = window.location.href;
    var $src = $(this).data("share");
    $url = encodeURI($url);
    console.log("this method will never called and gives you error Uncaught ReferenceError: shareURL is not defined");
    if ($src) {
      window.location.href = $url + $src;
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="shareURL(); return false;" data-share="https://www.facebook.com/sharer/sharer.php?u=" href="#">Share on Facebook</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多