[英]Javascript Onclick event error: $ is not defined
我试图在发生onclick事件时添加一些输入字段。 我正在使用javascript完成此操作。 当我尝试摆弄时,效果很好。 但是它不适用于我的本地主机。 我收到以下错误消息。
ReferenceError: $ is not defined
$(".more").click(function() {
这是我的代码:
<!DOCTYPE script PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<script src="//admin/lib/jquery-1.10.2.js" type="text/javascript">
</script>
<link href="//admin/css/layout.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(".more").click(function() {
$("#container").append("<br><div id='test'><label>Title: </label><input type=\"text\" id=\"txt_jobTitle\"> <label>Company</label><input type=\"text\" id=\"id2\"> <label>Started</label><input type=\"text\" id=\"txt_jobStarted\"> <label>Ended</label><input type=\"text\" id=\"txt_jobStarted\"> <div class='box'><a href='#'>x</a></div></div><br/>");
var count = $(".box").length;
});
$(".box a").live("click", function() {
$(this).parent().remove();
$("#test").remove();
});
</script>
</head>
<body>
<div id="container">
<a href="#" class="more">Add more +</a>
</div>
</body>
</html>
我不知道如何解决此问题,因为我不是javascript的关键角色。 我该如何解决这个问题?
我遇到了许多类似的解决方案,但都没有解决。
提前谢谢了。
我怀疑您的代码在包含jQuery
库之前已被调用,或者jQuery
js文件的路径错误/不正确。
尝试使用jQuery
代替$
like
jQuery(".more").click(function() {
//Do whatever
});
并确保已加载js
库文件(如jquery-1.10.2.js
,并将脚本放入DOM ready
。
您需要使用jQuery.noConflict()
因为您的jQuery library
与也使用$
其他库冲突。
并将代码包装在document.ready
就像jQuery一样,许多JavaScript库都将$用作函数或变量名。 在jQuery的情况下,$只是jQuery的别名,因此无需使用$即可使用所有功能。 如果您需要在jQuery旁边使用另一个JavaScript库,请通过调用$ .noConflict()将$的控制权返回到另一个库。 $的旧引用在jQuery初始化期间保存; noConflict()只是还原它们。
如果它比您的jQuery JS路径不正确,请尝试此操作
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
确保您为jquery使用了正确的路径,尝试像rajesh所说的那样从外部加载它,
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
并且如果您从外部加载jQuery 1.10.1
将会出现问题,您的live
函数将无法使用。
$(".box a").live("click", function() {
$(this).parent().remove();
$("#test").remove();
});
所以把它on()
$(document).on("click",".box a", function() {
$(this).parent().remove();
$("#test").remove();
});
这是小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.