How to set `data` attribute value to `option` when using knockout `options` binding

别等时光非礼了梦想. 提交于 2019-12-24 10:28:15

问题


In knockout's documentation, it mentions optionsAfterRender. I was trying to add data attribute value without succeed.

Here's the sample from the doc:

<select size=3 data-bind="
    options: myItems,
    optionsText: 'name',
    optionsValue: 'id',
    optionsAfterRender: setOptionDisable">
</select>

<script type="text/javascript">
    var vm = {
        myItems: [
            { name: 'Item 1', id: 1, disable: ko.observable(false)},
            { name: 'Item 3', id: 3, disable: ko.observable(true)},
            { name: 'Item 4', id: 4, disable: ko.observable(false)}
        ],
        setOptionDisable: function(option, item) {
            ko.applyBindingsToNode(option, {disable: item.disable}, item);
        }
    };
    ko.applyBindings(vm);
</script>

Here's what I tried but didn't work but also no errors.

setOptionDisable: function(option, item) {
    $(option).text(''); // this will blank out the text in options
    $(option).data('test', '123'); // but this won't do anything at all.
    $(option).attr('data-test', '123'); // this worked as pointed out by Matt
}

回答1:


jQuery actually assigns data attr but it does not show up on DOM element because jQuery saves it in an internal data structure. If you log your recent data attr you will get the value but you won't see on DOM.

Example :https://jsfiddle.net/kyr6w2x3/83/

But if you use attr() it does update the dom attribute as well.

Example https://jsfiddle.net/kyr6w2x3/84/



来源:https://stackoverflow.com/questions/39648731/how-to-set-data-attribute-value-to-option-when-using-knockout-options-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!