Javascript:对象中的范围问题
我无法从函数中访问某些变量。以下是我得到的:Javascript:对象中的范围问题,javascript,jquery,scope,prototype,Javascript,Jquery,Scope,Prototype,我无法从函数中访问某些变量。以下是我得到的: var PTP = function (properties) { this.errorsArray = [] } PTP.prototype.initHTMLItems = function () { $('input[data-widget-type="date"]').each(this.dateValidation) } PTP.prototype.dateValidation = function() { v
var PTP = function (properties) {
this.errorsArray = []
}
PTP.prototype.initHTMLItems = function () {
$('input[data-widget-type="date"]').each(this.dateValidation)
}
PTP.prototype.dateValidation = function() {
var field = '#' + $(this)[0].id
var that = this
$(field).focusout(function(){
var valid = form_validate_date($(field).val())
var label = $('#date').siblings('label').children('.label-text').text()
if (!valid) {
that.errorsArray.push({
'field': field,
'fieldType': 'date',
'errorMessage': 'Incorrect data' + (label !== undefined ? ' for ' + label : "")
})
}
})
}
问题是我无法访问errorsArray
我还尝试将回调函数作为参数传递给dateValidation:
PTP.prototype.addError = function(errorObj) {
this.errorsArray.push(errorObj)
}
试着这样做:
PTP.prototype.initHTMLItems = function () {
$('input[data-widget-type="date"]').each(this.dateValidation(this.addError))
}
PTP.prototype.initHTMLItems = function () {
$('input[data-widget-type="date"]').each(this.dateValidation.bind(this.addError))
}
也是这样:
PTP.prototype.initHTMLItems = function () {
$('input[data-widget-type="date"]').each(this.dateValidation(this.addError))
}
PTP.prototype.initHTMLItems = function () {
$('input[data-widget-type="date"]').each(this.dateValidation.bind(this.addError))
}
但这与日期验证中的范围有关:
PTP.prototype.dateValidation = function(callback) {
var field = '#' + $(this)[0].id
var that = this
$(field).focusout(function(){
var valid = form_validate_date($(field).val())
var label = $('#date').siblings('label').children('.label-text').text()
if (!valid) {
callback({
'field': field,
'fieldType': 'date',
'errorMessage': 'Incorrect data' + (label !== undefined ? ' for ' + label : "")
})
}
})
}
如何访问errorsArray?更改
$('input[data widget type=“date”]”)。每个(this.dateValidation)
到
然后更改PTP.prototype.dateValidation=function(回调){
toPTP.prototype.dateValidation=函数(元素){
现在,在dateValidation内部,
this
是您的PTP对象,element
是每个循环中的jquery元素如果我绑定到“this”,我可以访问errorsArray,但我无法访问正在处理的当前字段,这意味着var字段=“#”+$(this)[0].我不会work@MrCujo:啊,这是jquery api中非常烦人的一部分。我将更新我的答案(tl;dr您应该传入这两个参数)@MrCujo:updateEdit确实有效。我非常感谢您的时间。谢谢!只是想知道,是否可以通过关闭来解决此问题以保留范围?