YUI 3:将值设置为多选

YUI 3: Set Value to Multiple Select

本文关键字:设置 YUI      更新时间:2023-09-26

我使用YUI3,但我对YUI的使用有疑问。

我有一个带有一些选项标签的选择标签:

YUI().use( "node", "event", "cssbutton", function(Y){
    Y.one('body').addClass('yui3-skin-sam');
    
   Y.one('#btnSel2').on('click',function(){
   
        Y.one('#mySelect').set('value', '5');   
        
    });  
    
});
<select id="mySelect" size="10" multiple="true">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">PineApple</option>
<option value="4">Orange</option>
<option value="5">Peach</option>
    
</select>
<button id="btnSel2" class="yui3-button">Set Selected</button>

上面的方法只涵盖一个值,我可以从数组或逗号分隔的字符串中设置多个值吗?

如果检查yui3/build/dom-base/dom-base.js第202行,您将看到此功能未实现:

if (options && options.length) {
    // TODO: implement multipe select
    if (node.multiple) {
    } else if (node.selectedIndex > -1) {
        val = Y_DOM.getValue(options[node.selectedIndex]);
    }
}

以下是我们如何实现此功能:

YUI().use( "node", "event", "cssbutton", function(Y){
    Y.one('body').addClass('yui3-skin-sam');
    Y.DOM.VALUE_GETTERS.select = function(node) {
        var val = node.value,
            options = node.options;
        if (options && options.length) {
            if (node.multiple) {
                val = [];
                for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) {
                    if (option.selected) val.push(Y.DOM.getValue(option));
                };
            } else if (node.selectedIndex > -1) {
                val = Y.DOM.getValue(options[node.selectedIndex]);
            }
        }
        return val;
    };
    Y.DOM.VALUE_SETTERS.select = function(node, val) {
        if (node.multiple && !Y.Lang.isArray(val)) val = [val]; // Allow to set value by single value for multiple selects
        for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) {
            if ((node.multiple && val.indexOf(Y.DOM.getValue(option)) > -1) || (!node.multiple && Y.DOM.getValue(option) === val)) {
                option.selected = true;
                //Y_DOM.setAttribute(option, 'selected', 'selected');
            }
        }
    };
    
   Y.one('#btnSel2').on('click',function(){
   
        Y.one('#mySelect').set('value', ['1', '5']);   
        
    });  
    
});
<script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script>
<select id="mySelect" size="10" multiple="true">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">PineApple</option>
<option value="4">Orange</option>
<option value="5">Peach</option>
    
</select>
<button id="btnSel2" class="yui3-button">Set Selected</button>