gpt4 book ai didi

Javascript 作用域问题

转载 作者:行者123 更新时间:2023-11-29 17:31:03 26 4
gpt4 key购买 nike

我在 javascript 中遇到一些问题。我正在使用 jquery 插件编写一个类,它是我们下拉控件的包装器。

问题出在 loadJsonList 函数中,对 this.addOption(s.itemValue, s.itemText); 的调用不起作用,因为该方法不起作用存在。我知道 JS 的范围很奇怪,但我不知道如何在该范围内运行该函数??

jQuery.Class.extend("DDL",
{
id: '',
isTelerik: false
},
{
init: function (newid) {
this.Class.id = newid;

},
getValue: function () {
return $('#' + this.Class.id).val();
},
getText: function () {
return $('#' + this.Class.id + ' :selected').text();
},
setValue: function (newValue) {
try {
$('#' + this.Class.id).val(newValue);
} catch (err) {
alert(err);
}
},
setText: function (newText) {
try {
$('#' + this.Class.id + ' :selected').text(newText);
} catch (err) {
alert(err);
}
},
loadJsonList: function (list, param1, param2, param3) {
this.clearItems();

//init the service
var j = new JsonRPC();

// get the cut down data table
var dt = j.getDropDownData(list, param1, param2, param3);

// parse the datatable and load it into the telerik combo box
jQuery.each(dt, function (i, s) {
this.addOption(s.itemValue, s.itemText);
});
},
addOption: function (value, text) {
$('#' + this.Class.id).append('<option value="' + value + '">' + text + '</option>');
},
removeOption: function (value) {
$('#' + this.Class.id + ' option[value="' + value + '"]').remove();
},
clearItems: function () {
$('#' + this.Class.id + ' option').remove();
}
});

最佳答案

简单的一个。 JavaScript 使用函数级作用域,因此您可以使用其他名称保存对 this 变量的引用:

loadJsonList: function (list, param1, param2, param3) {
// save a reference for use in the each function later
var self = this;
this.clearItems();

//init the service
var j = new JsonRPC();

// get the cut down data table
var dt = j.getDropDownData(list, param1, param2, param3);

// parse the datatable and load it into the telerik combo box
jQuery.each(dt, function (i, s) {
// use self instead of this!
self.addOption(s.itemValue, s.itemText);
});
},

关于Javascript 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com