当事件处理程序设置非匿名函数时,访问$(this)
对象时发生错误。
function TextBoxChangeEventHandler(id)
{
var value = $(this).val();
//...do something
}
$("#object_position :input[type='text']")
.on("change", function(){TextBoxChangeEventHandler("id");});
//other some object set TextBoxChangeEventHandler...
错误日志:
未捕获的TypeError:无法读取属性' toLowerCase'未定义的 的jquery-2.1.1.min.js:4
有解决方法吗?
答案 0 :(得分:4)
试
function TextBoxChangeEventHandler(elem)
{
var value = $(elem).val();
//...do something
}
$("#object_position :input[type='text']")
.on("change", function(){TextBoxChangeEventHandler(this);});
答案 1 :(得分:2)
您可以使用.call()传递自定义执行上下文
function TextBoxChangeEventHandler() {
var value = $(this).val();
//...do something
}
$("#object_position :input[type='text']").on("change", function () {
TextBoxChangeEventHandler.call(this);
//with the update
TextBoxChangeEventHandler.call(this, 'id');
});
答案 2 :(得分:2)
通过引用传递TextBoxChangeEventHandler
函数。
$("#object_position :input[type='text']").on("change", TextBoxChangeEventHandler);
答案 3 :(得分:0)
您可以将TextBoxChangeEventHandler
的引用传递给您的方法。例如,
$("#object_position :input[type='text']").on("change", TextBoxChangeEventHandler);
答案 4 :(得分:0)
您可以使用jQuery代理 -
$("#object_position :input[type='text']")
.on("change", $.proxy(TextBoxChangeEventHandler("id"),this));