我有一个构造函数Dropdown
,它将数组作为参数。此参数将由附加到原型的方法使用。该参数是一个数组,应该将其转换为jQuery option
对象的参数,该参数应该是select元素的下拉菜单选项。目前我有:
function Dropdown(data) {
this.sel = $('<select>');
}
Dropdown.prototype.options = function (options) {
var self = this; //using $(this) doesn't work either
if ( !options ) {
//if null return the current values of
return self.sel.html();
} else {
//make a jQuery option object out of every item in the array
//set the sel property's html to that
self.sel.html = ($.map(options, function (val) {
return $('<option>').text(val).val(val);
}));
}
}
var testArray = ['one', 'two', 'three'];
var dropdown = new Dropdown(testArray);
dropdown.sel.appendTo($('body'));
console.log(dropdown.options()); //nothing outputted to the console
通过将testArray传递给Dropdown构造函数,这应该设置sel
的html属性,但它并没有尝试使用jQuery样式的getter向控制台输出任何内容。下拉列表附加到页面,没有选项。
答案 0 :(得分:2)
首先,您不是在原型中调用选项函数。在调用之后,出现了一些其他错误。
self.sel.html = ($.map(options, function (val) {
return $('<option>').text(val).val(val);
}));
这会将self.sel.html变成一个填充了jQuery选项元素的数组,而这些元素你什么都不做。
我稍微改了一下让它运转起来。看看它是否适合你。我相信这很容易理解。
function Dropdown(data) {
this.sel = $('<select>');
this.options(data);
}
Dropdown.prototype.options = function (options) {
var sel = this.sel;
options && options.forEach(function ( val ) {
$('<option>').val(val).text(val).appendTo(sel);
});
}
答案 1 :(得分:1)
现在你的构造函数除了在jQuery中创建一个select元素之外别无其他。您传入data
参数并且不执行任何操作。您只需在构造函数中添加this.options(data);
,就可以了。
function Dropdown(data) {
this.sel = $('<select>');
this.options(data);
}