使用KnockoutJS将2个选择组合成1个选择

时间:2014-11-12 21:40:00

标签: knockout.js

我的网页上有2个选择元素。有没有办法使用KnockoutJS将两个select元素中的select选项组合成1个select元素?

鉴于:(2选择)

<select id="select1">
    <option>One</option>
    <option>Two</option>
</select>


<select id="select2">
    <option>Three</option>
    <option>Four</option>
</select>

期望的结果:

<select id="select1">
    <option>Select 1</option> //if possible
    <option>One</option>
    <option>Two</option>
    <option>Select 2</option> //if possible
    <option>Three</option>
    <option>Four</option>
</select>

1 个答案:

答案 0 :(得分:1)

在javascript中:

var select1 = $('#select1'),
    select2 = $('#select2'),

    // create an array to bind
    options = ko.observableArray();

// this value doesn't exist in the dom
options.push('Select 1');

// add the text of all children to the array
select1.children().forEach(function(i, el) {
    options.push(el.innerText);
});

// this value doesn't exist in the dom
options.push('Select 2');

// add the text of all children to the array
select2.children().forEach(function(i, el) {
    options.push(el.innerText); 
});

// bind an options with the options property 
//  set to the options array to the dom
ko.applyBindings({ options: options });

在HTML中:

<select data-bind="options: options"></select>