javascript - W3Schools 示例不起作用?

标签 javascript jquery html

我正试图找出 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.2jQuery.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/

相关文章:

jquery - 删除后如何准确更新文本字段的属性?

javascript - 如果使用 jquery 选中,则取消选中复选框

html - 仅为移动设备更改 CSS?

javascript - 多选onchange事件jquery

javascript - addEventListener 在 useEffect Hook 中不起作用

javascript - 如何使用 jquery 从链接中获取值

javascript - 在本地或外部引用 javascript 库?

javascript - 搜索 JSON 以查找特定值

javascript - Wordpress WooCommerce 网格/列表切换 : How to trigger a button click?

javascript - 使用 form.serialize 获取正确的复选框值