我有一个在keyup
或change
上调用的函数,但我很难获得this
代码
var myNS = myNS || {};
myNS.validate = {
dobChange: function(elem){
console.log($(this).val().length); // trying to check length of "this"
}
}
$('.dob1-day, .dob1-month, .dob1-year').on('keyup change', myNS.validate.dobChange('foo'));
控制台错误:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
如何获取this
的价值?
答案 0 :(得分:3)
您应该从传递给处理程序的事件中提取DOM元素:
//getting the element
myNS.validate = {
dobChange: function(e){
console.log($(e.target).val().length); // trying to check length of "this"
}
}
//calling handler
$('.dob1-day, .dob1-month, .dob1-year').on('keyup change', myNS.validate.dobChange)
答案 1 :(得分:2)
{{1}}
答案 2 :(得分:1)
您可以使用call()
和匿名函数来设置相关上下文并传递额外的参数:
$('.dob1-day').on('keyup change', function(){myNS.validate.dobChange.call(this, "foo")});
答案 3 :(得分:0)
var myNS = myNS || {};
myNS.validate = {
dobChange: function($element){
console.log($element.val());
}
}
$(function () {
$(".content").on('keyup change','.dob1-day', function(){
myNS.validate.dobChange($(this));
});
});
<div class="content">
<input type="text" class="dob1-day">
</div>