[英]W3 Schools example not working?
我试图找出 W3 Schools 的这个例子,但据我所知,它不起作用。 如果我遗漏了什么,有人可以引导我吗?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#div1").on("click", function(){
$(this).css("background-color", "pink");
});
$("#div2").live("click", function(){
$(this).css("background-color", "pink");
});
});
</script>
</head>
<body>
<h4 style="color:green;">This example demonstrates how to achieve the same effect using on() and live().</h4>
<div id="div1" style="border:1px solid black;">This is some text.
<p>Click to set background color using the <b>on() method</b>.</p>
</div><br>
<div id="div2" style="border:1px solid black;">This is some text.
<p>Click to set background color using the <b>live() method</b>.</p>
</div>
</body>
</html>
小提琴: https : //jsfiddle.net/gratiafide/dwmwm43a/
来源: http : //www.w3schools.com/jquery/tryit.asp? filename= tryjquery_event_on_live
这是因为jQuery.fn.live(..);
已在 1.7 版中弃用,并在 1.9 版中完全删除。
您正在使用jQuery 1.12.2
方法jQuery.fn.live(...);
此版本的 jQuery 中不存在。
获取jQuery.fn.live(...);
要工作,您必须将script
元素更改为:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.min.js"></script>
如果您想使用最新版本的 jQuery,请改用:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script>
$(document).ready(function() {
$("#div1").on("click", function() {
$(this).css("background-color", "pink");
});
});
</script>
</head>
<body>
<div id="div1" style="border:1px solid black;">
Hello World!
<p>Click me to make me pink!</p>
</div>
</body>
</html>
从 jQuery 1.7 开始,不推荐使用.live()
方法。
在您的小提琴中,您使用的是 v1.12.2
与 w3c 相同:
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
因此,将 src 更改为:
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"
它有效
不再推荐使用 .live() 方法,因为更高版本的 jQuery 提供了没有缺点的更好的方法。
来源: http : //api.jquery.com/live/
请注意:您的示例并非来自 W3C(请参阅您提供的标题)。 您引用了 w3schools 并在 stackoverflow 上检查了其他问题,您会发现 w3c 和 w3school 之间没有从属关系(前两个字符除外)。
还要确保您查看 w3schools 浏览器支持以查看它是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.