本文介绍了当使用knockout`options`绑定时,如何将`data`属性值设置为`option`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在淘汰赛的中,它提到 optionsAfterRender 。我试图添加数据属性值而没有成功。

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

以下是来自doc的样本:

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
}


推荐答案

jQuery实际上分配了数据attr 但它没有出现在 DOM 元素上,因为jQuery将它保存在内部数据结构。
如果您记录最近的数据attr,您将获得该值,但您将看不到DOM。

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.

示例:

但如果你使用 attr()它也会更新dom属性。

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

示例

这篇关于当使用knockout`options`绑定时,如何将`data`属性值设置为`option`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:39