如何在 Javascript 中访问事件监听器中的变量
我需要在我的 JavaScript 中从某种“监听器”(对于 Facebox)访问一些变量。如何在 JavaScript 函数和事件侦听器之间传递变量?
我一直在搞乱范围,但似乎声明全局变量有点老套,尤其是当您开始考虑其他控件(即模式中结果的分页)时,这些控件不会像全局变量那样好变量。
这是给我带来问题的部分:
function song_clarify ()
{
// this launches a modal window, fills with html.
$.facebox('<div id="search"><div></div></div>');
}
// AJAX function. when called, this loads the required htmls into the modal
function clarify_loader()
{
var loadUrl = "ajax/clarify";
$("#search > div")
.html(ajax_load)
.load(loadUrl, 'search='+source+'&searchTerm='+song);
}
// Waits for the modal to be revealed before calling AJAX function.
// (if function called outside listener, nothing for the AJAX to bind to as modal appears dynamically)
$(document).bind('reveal.facebox', function() {
// Problem is here. Need to be able to do clarify_loader(source,song)
clarify_loader();
})
I need to access some variables from within a 'listener' of sorts (for Facebox) in my javascript. How do I communicate variables between javascript functions and event listeners?
I have been messing about a bit with scope, but it seems that declaring global variables is a bit hacky, especially once you start factoring in other controls (ie. pagination for my results within the modal) that wouldn't sit so well as global variables.
This is the section that is causing me problems:
function song_clarify ()
{
// this launches a modal window, fills with html.
$.facebox('<div id="search"><div></div></div>');
}
// AJAX function. when called, this loads the required htmls into the modal
function clarify_loader()
{
var loadUrl = "ajax/clarify";
$("#search > div")
.html(ajax_load)
.load(loadUrl, 'search='+source+'&searchTerm='+song);
}
// Waits for the modal to be revealed before calling AJAX function.
// (if function called outside listener, nothing for the AJAX to bind to as modal appears dynamically)
$(document).bind('reveal.facebox', function() {
// Problem is here. Need to be able to do clarify_loader(source,song)
clarify_loader();
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您使用的示例中, $(document).bind('reveal.facebox', function() {}) 之外的 var 将是正确的设计。此链接可能会有所帮助:
http://api.jquery.com/bind/
转到名为的部分“传递事件数据”
In the example you have used, a var outside of the the $(document).bind('reveal.facebox', function() {}) would be the correct design. This link might help:
http://api.jquery.com/bind/
Go to the section called "Passing Event Data"
好吧,您没有提供声明源和歌曲变量的位置。如果它们来自用户填写的输入,那么我相信你不会有问题。如果您在clarify_loader中分配值,则只需使用全局变量
,然后当您分别调用函数a和b时,您的变量将具有值x和y。
Well, you did not provide from where source and song variables are declared. If they are coming from an input filled by a user then I believe you'd have no problem. If you're assigning the value within clarify_loader then just use global variables
and then when you call functions a and b respectively your variables will have the value x and y.