为什么我不能使用onClick来执行jQuery $(document).ready函数内的函数? [英] Why can't I use onClick to execute a function inside a jQuery $(document).ready function?

查看:204
本文介绍了为什么我不能使用onClick来执行jQuery $(document).ready函数内的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Javascript和jQuery的新手。我想单击一个按钮并执行js功能。 (对于这个例子,它只是一个警报,但它实际上是一个ajax函数。)

I'm new to Javascript and jQuery. I want to click a button and have a js function executed. (For this example, it's just an alert, but it's actually an ajax function.)

出现第一个警报,但是在我点击按钮后,我从未看到第二个警告(做到了)提醒。看起来javascript不认为单击按钮时定义了doIt()函数。

The first alert appears, but after I click the button, I never see the second ("did it") alert. It looks like javascript doesn't think the doIt() function is defined when the button is clicked.

以下是相关代码:

$(document).ready(function()
{ 
    alert('ready');

    function doIt() {
        alert('did it');
    };
}
)

<body>
    <input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>


推荐答案

这是因为该功能不在全局范围内,这是你的 onclick =正在寻找的地方。你需要将它移到 document.ready 之外(所以它不是专门针对那个闭包的),或者(一种更好的方法IMO)将它绑定在 document.ready ,这是我的意思:

It's because that function isn't in a global context, which is where your onclick="" is looking for it. You need to move it outside your document.ready (so it's not scoped exclusively to that closure), or (a better approach IMO) bind it inside the document.ready, here's what I mean by each:

将其绑定(删除)你的 onclick =:)

Binding it inside (remove your onclick="" for this):

$(document).ready(function() { 
  alert('ready');
  $("input[name='Go']").click(doIt);
  function doIt() {
    alert('did it');
  }
});

或匿名版本(再次删除 onclick =):

or the anonymous version (again remove your onclick=""):

$(document).ready(function() { 
  alert('ready');
  $("input[name='Go']").click(function() {
    alert('did it');
  });
});






或者将其搬到外面(保留你的<$ c) $ c> onclick =):

$(document).ready(function() { 
  alert('ready');
});
function doIt() {
  alert('did it');
}

这篇关于为什么我不能使用onClick来执行jQuery $(document).ready函数内的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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