我需要访问$( document ).ready()
范围内外的元素。
假设以下代码:
var text__holder = $('#text__holder');
$(function() {
text__holder.text('Inside DOM ready');
/*
SOME MORE ACTION WITH ELEMENT
*/
});
var writeSomeTxt = function () {
text__holder.text('Outside DOM ready');
};
writeSomeTxt();
在这种情况下,我无法访问函数内部的元素。 JS也在外部.js
文件中,该文件包含在页面的<head>
部分中,我无法在其他地方替换它。
我目前的“解决方法”是:
var text__holder = $('#text__holder');
$(function() {
text__holder.text('Inside DOM ready');
/*
SOME MORE ACTION WITH ELEMENT
*/
});
var writeSomeTxt = function () {
$(function() {
text__holder.text('Outside DOM ready');
});
};
writeSomeTxt();
答案 0 :(得分:4)
问题很可能不仅仅是这行代码:
var text__holder = $('#text__holder');
在DOM加载之前。如果这样做,你只需要一个空的jQuery对象,因为它找不到任何匹配的DOM对象。
如果您知道在加载DOM之后才会调用writeSomeTxt()
,那么您可以这样做:
var text__holder;
$(function() {
text__holder = $('#text__holder');
text__holder.text('Inside DOM ready');
/*
SOME MORE ACTION WITH ELEMENT
*/
});
var writeSomeTxt = function () {
text__holder.text('Outside DOM ready');
};
// don't call this until after the DOM is loaded
// presumably based on some DOM event
writeSomeTxt();
但是,实际上,尝试缓存单个DOM引用是没有意义的,所以编写代码的更好方法是:
$(function() {
$('#text__holder').text('Inside DOM ready');
/*
SOME MORE ACTION WITH ELEMENT
*/
});
var writeSomeTxt = function () {
$('#text__holder').text('Outside DOM ready');
};
// don't call this until after the DOM is loaded
// presumably based on some DOM event
writeSomeTxt();
或者,如果所有这些代码都应该在页面初始化时运行,那么只需将它全部放在.ready()
处理程序中。
$(function() {
var text__holder = $('#text__holder');
text__holder.text('Inside DOM ready');
/*
SOME MORE ACTION WITH ELEMENT
*/
var writeSomeTxt = function () {
text__holder.text('end of DOM ready');
};
writeSomeTxt();
});
答案 1 :(得分:2)
您可以在document.ready
之外声明函数和变量,并在定义变量后定义内部变量以及调用函数:
var text__holder;//declare undefined varible
$(function() {
text__holder = $('#text__holder');// can now define varible
text__holder.text('Inside DOM ready');
// call function now that variable is defined
writeSomeTxt();
});
var writeSomeTxt = function () {
text__holder.text('Outside DOM ready');
};