我正试图找出 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>
fiddle :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>
关于javascript - W3Schools 示例不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37473686/