当包含在单独的文件中时,为什么jQuery单击不起作用 [英] Why jQuery click doesn't work when included in a separate file

查看:105
本文介绍了当包含在单独的文件中时,为什么jQuery单击不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个学习jQuery和Web开发的初学者,所以这可能是一个愚蠢的问题,但是我无法在Google上找到答案(很可能是我没有在搜索正确的关键字).我有一个简单的HTML文件(例如,"test.html")可以加载jQuery,还有一个我编写的外部javascript文件(例如"test.js"),并且其中有一个按钮.例如,

I am a beginner learning jQuery and web development, so this may be a dumb question, but I cannot find an answer to this on Google (probably I'm not searching for the right keywords). I have a simple HTML file (say, 'test.html' that loads jQuery, an external javascript file (say, 'test.js') that I wrote, and have a button in it. For example,

<html>
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="scripts/test.js" type="text/javascript"></script>
....
<body>
<button type="button" class="button" id="my_button">test</button>
</body>
</html>

在"test.js"中,我有:

In 'test.js', I have:

$( "#my_button" ).click(function() {
    alert('test');
    return false;
});

但是当我单击按钮时,它不起作用.但是,当我将"test.js"中的内容放入"test.html"中时,如下所示:

But when I click on the button, it doesn't work. However, when I put what's in 'test.js' in 'test.html' like this:

<html>
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $( "#my_button" ).click(function() {
        alert('test');
        return false;
    });
});
</script>
....
<body>
<button type="button" class="button" id="my_button">test</button>
</body>
</html>

有效.第一个问题是:有人可以解释一下为什么在我将代码插入外部文件并加载时它可以工作吗?

It works. First question is: Can someone explain me why it would work when I insert the code in external file and load it? Is that always necessary to wrap jQuery code with $(function() {......} for it to work?

理想情况下,我不希望HTML模板中包含JavaScript代码,因为它显然很乱.相关/第二个问题是:分离上述javascript/jQuery代码并使其在预期的HTML模板中工作的最干净/最好的方法是什么?

Ideally, I don't want javascript code in my HTML template because it's obviously messy. Related/second question is: What is the cleanest/best way to separate the javascript/jQuery code like above and yet make it work in the intended HTML template?

谢谢您的回答.

推荐答案

点击功能需要使用$(function(){...}).它告诉jquery文档已加载,并且可以开始在DOM上工作.在此之前,DOM还没有准备好,您的元素可能不存在.

You need to have $(function() { ... }) for your click function to work. It tells jquery that the document is loaded and it can start working on the DOM. Before then, the DOM is not ready and your element might not exist.

编辑:也可以将其用于外部文件,除非您更高级并且知道何时不使用它.

Use this for your external files too, unless you are more advanced and know when NOT to use it.

这篇关于当包含在单独的文件中时,为什么jQuery单击不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆