简体   繁体   English

Javascript和Jquery定义一个全局变量?

[英]Javascript & Jquery defining a global variable?

I am trying to define a global jquery object variable so that I can access it from different functions. 我试图定义一个全局jquery对象变量,以便我可以从不同的函数访问它。

This is what I am doing: 这就是我在做的事情:

var object_list = $("#object_list");
var list_length = object_list.find("li").length;

$(document).on('keydown', '#object_list', function(event) {
    //both of these don't work
    alert(object_list);
    alert(list_length);
});

Well,, for some reason this is not working (the first alert gives me NULL and the second gives me 0, which is not). 好吧,由于某种原因,这是行不通的(第一个警报给我NULL,第二个给我0,这不是)。

Why aren't my global variables working..?? 为什么我的全局变量不起作用.. ??

Thanks!! 谢谢!!

This isn't a scope issue - there's a typo in your code: 这不是范围问题 - 您的代码中存在拼写错误:

var object_list = $("#object__list"); // 2 underscores

$(document).on('keydown', '#object_list', function(event) { // 1 underscore

So long as object_list and list_length are declared in a parent function this should work. 只要在父函数中声明了object_listlist_length ,这应该可行。

Alternatively, you could attach the variables to the window object, so they can be used anywhere at all in your code: 或者,您可以将变量附加到window对象,因此可以在代码中的任何位置使用它们:

window.object_list = $("#object__list");
window.list_length = object_list.find("li").length;

As stated though, this should not be necessary given your code in the OP. 如上所述,鉴于OP中的代码,这不应该是必要的。

What about this: 那这个呢:

var object_list;
var list_length;

$(document).ready(function() {
    object_list = $("#object__list");
    list_length = object_list.find("li").length;
});

$(document).on('keydown', '#object_list', function(event) {
    alert(object_list);
    alert(list_length);
});

You're delegating event handling to document , and I assume that's because that #object_list does not exist in the page at the moment you bind the event. 您将事件处理委托给document ,我认为这是因为绑定事件时页面中不存在#object_list If it also doesn't exist at the moment you define object_list and list_length , that's why they're empty. 如果在定义object_listlist_length它也不存在,那就是它们为空的原因。 And once empty, they won't be populated automatically when the elements are added. 一旦清空,添加元素时不会自动填充它们。 Try this: 尝试这个:

$(document).on('keydown', '#object_list', function(event) {
    alert(this);
    alert($(this).find('li').length);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM