【问题标题】:W3 Schools example not working?W3Schools 示例不起作用?
【发布时间】:2016-05-27 02:06:28
【问题描述】:

我试图找出 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

【问题讨论】:

  • W3schools 通常很简单,但已经过时,有时不正确地使用参考网站,而不是像 MDN 或 jQuery 文档。

标签: javascript jquery html


【解决方案1】:

这是因为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>

【讨论】:

【解决方案2】:

从 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"

它可以工作

http://api.jquery.com/live/

【讨论】:

【解决方案3】:

不再推荐使用 .live() 方法,因为更高版本的 jQuery 提供了没有缺点的更好方法。

来源:http://api.jquery.com/live/

【讨论】:

  • 我在编辑中添加了源代码。谢谢你告诉我@hlfrmn
【解决方案4】:

请注意:您的示例并非来自 W3C(请参阅您给出的标题)。您引用了 w3schools 并检查了 stackoverflow 上的其他问题,您会发现 w3c 和 w3school 之间没有从属关系(前两个字符除外)。

【讨论】:

  • 嘿@Peter,Stack Overflow 有一项政策,即答案应该包含问题的潜在解决方案。评论和其他非答案应保留为 cmets。
  • 嘿@T0xicCode,我知道这项政策,但我被另一项政策阻止:当我尝试评论原始问题时,我收到“您必须有 50 名声望才能发表评论”。
  • 偏离路线 - 我过去也做过同样的假设(并且被 w3schools 的坏例子浪费了时间)。
【解决方案5】:

还要确保你在 w3schools 浏览器支持中查看它是否可以工作

【讨论】:

    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多