0

The code in a file on my computer

<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <link rel="stylesheet" href="style.css" type="text/css">
    <script>
    $("#word").blur(function() {
alert('test');
$("#fo").innerHtml("focusout fired");}
);
</script>
</head>

<body>
<div id='word' contenteditable="true" title="Character Name"></div>
<div id='foo'>Foo</div>
</body>

The Jfiddle

This code works (partly) in jfiddle, it will fire the event but not change the content of the foo div. So questions are:

  • Why isn't it changing the content of the div in the fiddle.
  • Why does the code on my local computer not work?
4

2 回答 2

3

You need to enclose your jquery code in $(function(){}) for it to work on your local. Also, change #fo to #foo

<script>
$(function(){
    $("#word").blur(function () {
        $("#foo").html("focusout fired");
    });
});
</script>

Check this fiddle

Also, note that i changed innerHtml() to html()

于 2013-06-01T01:41:19.597 回答
1

默认情况下,JSFiddle 将您的 JS 代码包装在一个onload处理程序中 - 请参阅页面左侧“框架和扩展”下的第二个下拉菜单 - 这意味着您的代码在整个页面(所有元素)之后才会执行已加载并解析。

在您的页面上您还没有这样做,因此因为您的脚本块位于顶部,所以它在页面的其余部分被解析之前运行并且浏览器还不知道该"#word"元素。

这就是为什么您的小提琴有效但您的本地项目无效的原因。

您可以通过将脚本块移动到正文的末尾或将代码包装在文档就绪处理程序中来解决此问题,以便它在页面的其余部分被解析后运行。

$(document).ready(function() {
    $("#word").blur(function () {
        alert('test');
        $("#foo").html("focusout fired");
    });
});

在大多数情况下,jQuery 的 document ready 比onload处理程序更好,因为它会在页面被解析后立即触发,而无需等待 img 或 iframe 元素加载。

任何好的 jQuery 教程都会解释处理程序$(document).ready()使用。

于 2013-06-01T01:47:59.413 回答