gpt4 book ai didi

javascript - 如何修复这个 jQuery 范围错误?

转载 作者:行者123 更新时间:2023-11-28 16:31:28 25 4
gpt4 key购买 nike

有些东西我无法在这段代码中弄清楚,我认为这是一个范围问题。

我有以下 JavaScript 代码段

<javascript language="javascript>
$(function() {
$("#dialog").dialog({
autoOpen: false
});

function getMessage(direction, msgId) {
return "This is an " + direction + " message with ID: " + msgId;
}

function showMessage(direction, msgId) {
$("#dialog").text(getMessage(direction, msgId));
$("#dialog").dialog('open');
}
});
</script>

我想这样调用它

<div id="dialog" title="Message Info"></div>
<input type="button" id="btnCommand1" value="Command 1" onclick="javascript: showMessage('Outgoing', 1000487874')" />
<input type="button" id="btnCommand2" value="Command 2" onclick="javascript: showMessage('Incoming', 2000237851')" />

我知道我也可以通过 jQuery 绑定(bind)点击事件,但是因为我动态创建这些按钮,所以我需要像上面提到的那样调用它。问题我收到一个错误,表明 showMessage() 未定义。我发现,一般来说,在 jQuery 范围 $(function(){}) 内定义的方法无法从该范围之外访问!怎么解决这个问题?

最佳答案

javascript:

这是一个label并不意味着“这是 JavaScript 代码”。您specify that onclick attributes contain JavaScript带有元数据。

because I create those buttons dynamically I need to call it like mentioned above.

这是一个错误的前提。

I found that in general methods defined within jQuery scope $(function(){}) are not accessible from outside this scope! how to solve this?

将函数移到匿名函数之外

关于javascript - 如何修复这个 jQuery 范围错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788800/

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