jquery - 未定义 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中一样。
解决方案
您必须将您的 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>
推荐阅读
- p5.js - 如何在 p5.js 和 matter.js 中用图像填充形状
- android - 在 EditText 中设置文本会重置光标并关闭来自键盘的建议
- reactjs - 我正在使用 TypeScript 和 React,我需要检测文档中动态创建的元素的点击
- python - 从 Jupyter 交互式登录到 Azure 以从密钥保管库中获取 Secret
- asp.net-mvc - Asp.net MVC 中的 Paypal payflow pro
- java - 在Java中将时间戳UTC转换为PST
- node.js - 如何解决您的函数被杀死,因为它在我的 Firebase 模拟器中引发了未处理的错误?
- python - 迁移后数据库中的表未在数据库中创建并在 Django 中迁移
- angular - 在创建 get Observable Angular 后添加 http 标头
- javascript - 获取要在 if 语句中使用的返回值