Javascript 单例类没有从 DOM 属性中获取值?



数据属性是使用 Django 渲染的 jinja 设置的。当我尝试访问数据网址属性时,该值被分配给类的 URL 对象。

我对这段代码有两个问题。 首先,当我尝试访问数据默认属性时,它会返回 null 或未定义的值。 其次,当我尝试将来自 ajax 调用的响应分配给 this.data 时,它没有被分配。

下面是我的代码

<select id="value" data-url="api/values" data-default="1">
</select>

$(document).ready(function(){

var value = new function(){
this.url = $("#value").attr("data-url");
this.default = $("#value").attr("data-default");
this.data = null;
this.settings =   {
"async": true,
"crossDomain": true,
"url": this.url,
"method": "GET",
};
this.getData = function(){
$.ajax(this.settings).done(function(response){
this.data = response;
$.each(response, function (i, value) {
var $option =  $('<option>').text(value.shift_name)
.attr('value', value.id)
.attr('start', value.shift_start_time)
.attr('end', value.shift_end_time)
.attr('shift_day', value.shift_day)
if (this.default==value.id){        //Error here this.default is always undefined 
$option.attr('selected', 'selected');
}
$('#value').append($option);
});//Loop ends
});//ajax ends
}//sub function ends
} //class ends
value.getData();
});

您有两个不同的作用域,因此需要执行以下操作:

$(document).ready(function(){

var value = new function(){
this.url = $("#value").attr("data-url");
this.default = $("#value").attr("data-default");
this.data = null;
this.settings =   {
"async": true,
"crossDomain": true,
"url": this.url,
"method": "GET",
};
var outerScope = this;
this.getData = function(){
$.ajax(this.settings).done(function(response){
outerScope.data = response;
$.each(response, function (i, value) {
var $option =  $('<option>').text(value.shift_name)
.attr('value', value.id)
.attr('start', value.shift_start_time)
.attr('end', value.shift_end_time)
.attr('shift_day', value.shift_day)
if (outerScope.default==value.id){        
$option.attr('selected', 'selected');
}
$('#value').append($option);
});//Loop ends
});//ajax ends
}//sub function ends
} //class ends
value.getData();
});

最新更新