gpt4 book ai didi

javascript - 为什么我不能使用 onClick 来执行 jQuery $(document).ready 函数内的函数?

转载 作者:行者123 更新时间:2023-11-28 06:55:02 26 4
gpt4 key购买 nike

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

出现第一个警报,但在单击按钮后,我再也没有看到第二个(“did it”)警报。看起来 JavaScript 认为单击按钮时并未定义 doIt() 函数。

相关代码如下:

$(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 更好的方法)将其绑定(bind)在 document.ready 内,这就是我所说的每一个的意思:

<小时/>

将其绑定(bind)到内部(为此删除 onclick=""):

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

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

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

或者将其移到外面(保留 onclick=""):

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

关于javascript - 为什么我不能使用 onClick 来执行 jQuery $(document).ready 函数内的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32629642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com