首页 > 解决方案 > 未定义 onclick 功能

问题描述

我有这个相当简单的函数,我想用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中一样。

标签: jquery

解决方案


您必须将您的 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>

下面将不起作用,因为共享 url 的范围仅限于 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>


推荐阅读