这是代码的一个非常简化的版本来解释我的问题。jquery对象不能作为全局变量工作
HTML:
<input type="radio" name="enableDisableBox" id="radioDisable" checked="checked" />
Disable
<br />
<input type="radio" name="enableDisableBox" id="radioEnable" />
Enable
<br />
<input type="text" id="txtUserInput" disabled="disabled" />
的JavaScript:
var txtInputObj2 = $("#txtUserInput");
function init1() {
var txtInputObj1 = $("#txtUserInput");
$("input[name='enableDisableBox']:radio").change(function() {
if ($("#radioEnable").attr("checked"))
txtInputObj1.removeAttr("disabled").focus();
else
txtInputObj1.attr("disabled", "disabled");
});
}
function init2() {
$("input[name='enableDisableBox']:radio").change(function() {
if ($("#radioEnable").attr("checked"))
txtInputObj2.removeAttr("disabled").focus();
else
txtInputObj2.attr("disabled", "disabled");
});
}
$(document).ready(function() {
init1();
//init2();
});
如果我运行INIT2功能,它并没有给我任何的错误,但不启用或禁用任何文本框我。
如果您注意到,txtInputObj1在init1函数中定义,并且txtInputObj2被定义为全局变量。
关于如何使jQuery选择器对象全局的任何建议?
在DOM准备好之前,您正在执行'$(“#txtUserInput”)'*'。该元素尚不存在。 –
你在哪里声明你的jQuery?我见过一些人在html脚本的底部删除了jQuery(通常在'