简体   繁体   English

为什么匿名函数在 Javascript 中对我不起作用?

[英]Why doesn't anonymous function work for me in Javascript?

I am new to Javascript, and I am trying to get this function to work, but what ever I do I can't get anonymous functions to work, when I switch to the normal function it works.我是 Javascript 的新手,我试图让这个函数工作,但是无论我做什么,我都无法让匿名函数工作,当我切换到它工作的正常功能时。 I know that I can live without anonymous functions but it's really annoying me.我知道没有匿名函数我也能活,但这真的让我很烦。

Example:示例:

In the HTML file:在 HTML 文件中:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript" src="ch10_2.js"> </script>
<body>
<a href="http://www.google.com" id="search_link">Go Searching</a> 
</body>
</html>

In the JavaScript file:在 JavaScript 文件中:

var s_link = document.getElementById("search_link"); 

s_link.onclick = function() {  
      var is_sure = window.confirm("Are you sure you want to leave?"); 
      if (!is_sure) { 
        window.alert("OK. You can stay here."); 
        return false; 
      } 
    };

There are several problems here, each on its own would cause this script to fail:这里有几个问题,每个问题都会导致这个脚本失败:

  • Script tag is an illegal position in the document - between the <body> and <head> tags. Script 标签是文档中的非法位置 - <body> 和 <head> 标签之间。 It must be inside one of those.它必须在其中之一中。
  • Script tries to access a variable named 's_link' which should point to the link.脚本尝试访问名为“s_link”的变量,该变量应指向链接。 For it to reference the link, you need to fetch the element using something like getElementById() or other DOM traversal methods [Edit - I see you've added that line after posting the question].为了让它引用链接,您需要使用类似 getElementById() 或其他 DOM 遍历方法 [编辑 - 我看到您在发布问题后添加了该行] 来获取元素。
  • If the script is ran before the the element (link) is rendered (as it is now), it would not affect the element since it does not exist in the document yet.如果在呈现元素(链接)之前运行脚本(就像现在一样),它不会影响该元素,因为它还不存在于文档中。 Either wrap it in a function that runs on document load, or place the script after the element in the document.要么将它包装在一个在文档加载时运行的函数中,要么将脚本放在文档中的元素之后。

The link with the id search_link doesn't exist at the time the script runs, so it can't be fetched with getElementById or similar.脚本运行时,id 为search_link的链接不存在,因此无法使用 getElementById 或类似方法获取。 You need to delay the execution of the code (eg by wrapping it in a function that executes onload or just moving the <script> element to after the link is parsed (just before </body> is often recommended).您需要延迟代码的执行(例如,通过将其包装在一个执行onload的函数中或仅将<script>元素移动到链接被解析之后(通常建议在</body>之前)。

It works for me.它对我有用。

Suggestion: Make sure to put your code at the end of the page just before </body> .建议:确保将您的代码放在页面末尾的</body>之前。

You should tell your script to execute after the page has loaded .您应该告诉您的脚本在页面加载后执行 To do this just wrap the code as shown below:为此,只需将代码包装如下:

window.onload = function() { 
    // code you had before
}

The reason for this is simple.原因很简单。 The script is currently being executed before the page is loaded.当前正在加载页面之前执行脚本。 As such the document.getElementById() request is actually failing.因此document.getElementById()请求实际上失败了。 It has nothing to do with your function being anonymous.这与您的匿名函数无关。

Just as Mr. Dorward pointed out, your script (at ch10_2.js) is executed before de DOM is ready.正如 Dorward 先生指出的那样,您的脚本(在 ch10_2.js 处)在 de DOM 准备就绪之前执行。 The thing is, to attach an event to an element said element must exist but as javascript code is executed as soon as it is loaded the rest of the page is usually still loading.问题是,要将事件附加到元素上,该元素必须存在,但由于 javascript 代码在加载后立即执行,因此页面的其余部分通常仍在加载。 Therefore, the element you want to attach an event to does not exist yet.因此,您要将事件附加到的元素尚不存在。

I recommend this article about how jQuery (a javascript library) deals with this: http://www.learningjquery.com/2006/09/introducing-document-ready .我推荐这篇关于 jQuery(一个 javascript 库)如何处理这个问题的文章: http : //www.learningjquery.com/2006/09/introducing-document-ready

And here is a jsbin very simple example: http://jsbin.com/eziwu5/edit这是一个 jsbin 非常简单的例子: http ://jsbin.com/eziwu5/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM