javascript 使用淘汰赛选择默认选项值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21146809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:12:50  来源:igfitidea点击:

Selecting default option value with knockout

javascriptknockout.js

提问by shriek

I'm trying to select a default select option based on one of the property with which I'm populating my select option.

我正在尝试根据用于填充选择选项的属性之一来选择默认选择选项。

This code is copied straight from @rneimeyer's fiddle. I did tweak it to do what I wanted to do.

此代码直接从@rneimeyer 的 fiddle复制。我确实调整了它来做我想做的事。

So, I have choices as my observableArray.

所以,我可以选择作为我的 observableArray。

var choices = [
    { id: 1, name: "one", choice: false },
    { id: 2, name: "two", choice: true },
    { id: 3, name: "three", choice: false }
    ];

function ViewModel(choices, choice) {
   this.choices = ko.observableArray(choices);
};

The difference between rneimeyer's fiddle and mine is that I have choiceproperty added on my object inside the observableArray instead of having a separate observable for the option that we want to be default.

rneimeyer 的小提琴和我的小提琴之间的区别在于,我choice在 observableArray 内的对象上添加了属性,而不是为我们希望成为默认选项的选项设置单独的 observable。

Here's the fiddleon my attempt.

这是我尝试的小提琴

Now I'm checking in my select element tag whether the choiceattribute is true or not. And if it is then I want to set the nameto the valueattribute so that it becomes the default.

现在我正在检查我的 select 元素标签该choice属性是否为真。如果是,那么我想将 设置name为该value属性,使其成为默认值。

<select data-bind="options: choices, optionsText: 'name', value: choice"></select>

I've tested this with simple data model in my fiddlehere as well which is working just as I wanted.

我已经在我的小提琴中使用简单的数据模型对此进行了测试,这正如我想要的那样工作。

I guess what my real query is how to check choiceproperty in the data-bind. I see that optionTextis being able to access the nameproperty just fine. Not sure why it isn't same for choiceproperty in valueattribute.

我想我真正的查询是如何检查choice数据绑定中的属性。我看到optionText能够访问该name属性就好了。不知道为什么choice属性中的value属性不一样。

回答by shriek

I might have misdirected to some people. Also, I apologize for not mentioning the version that I'm using. I'm currently using Knockout 3.0.0 (you'll see why this is important later)

我可能误导了某些人。另外,我很抱歉没有提到我正在使用的版本。我目前正在使用 Knockout 3.0.0(稍后您会明白为什么这很重要)

Also, just to note that I'm not saying @XGreen's method is wrong but that wasn't exactly what I was looking for and this might be due to my poor explanation.

另外,请注意,我并不是说@XGreen 的方法是错误的,但这并不是我想要的,这可能是由于我的解释不当。

Let me first try to clarify what I was trying to accomplish. First of all, I will be having an array of object with the information for the options.

让我首先尝试澄清我试图完成的任务。首先,我将拥有一个包含选项信息的对象数组。

[
 { id: 1, name: "one", choice: false },
 { id: 2, name: "two", choice: true },
 { id: 3, name: "three", choice: false }
]

Now, what I wanted to do was to data-bind select option to that array with choice true being the default selected one.

现在,我想要做的是将选择选项数据绑定到该数组,其中选择 true 是默认选择的选项。

I'm not intending to create any extra observable except the array itself which is going to be an observableArray.

除了将成为 observableArray 的数组本身之外,我不打算创建任何额外的 observable。

After much research I finally found optionsAfterRenderattribute for optionsproperty in Knockout's Docs.

经过大量研究,我终于在Knockout 的 Docs 中找到了optionsAfterRender属性的options属性。

<select data-bind="options: choices, 
                   optionsValue: 'name',
                   optionsAfterRender: $root.selectDefault">
</select>

So what optionsAfterRender really does is, on each array element it calls custom function which I've set to check if the choiceis true or not and make the value of select option that which has the true.

所以 optionsAfterRender 真正做的是,在每个数组元素上,它调用我设置的自定义函数来检查它是否choice为真,并使 select 选项的值具有真值。

Do note that ko.applyBindingsToNodedoes notwork on version 2.2.0 which I had in my original fiddle.

请注意,这ko.applyBindingsToNode不适用于我在原始小提琴中使用的 2.2.0 版。

function ViewModel(choices) {
   this.choices = ko.observableArray(choices);
    this.selectDefault = function(option,item){
        if(item.choice){
            ko.applyBindingsToNode(option.parentElement, {value: item.name}, item);
        }
    };
};
ko.applyBindings(new ViewModel(choices));

And here's the fiddlefor it.

这是它的小提琴

回答by Ali Habibzadeh

Ok If I understand you want to set the true choice as your default selected value.

好的,如果我明白您想将真正的选择设置为您的默认选择值。

First you need to involve idin your drop down so it becomes the value of the options as we will filter our collection based on that unique id

首先,您需要参与id您的下拉列表,以便它成为选项的价值,因为我们将根据该独特的内容过滤我们的收藏id

<select data-bind="options: choices, optionsText: 'name', optionsValue: 'id',  value: selectedChoice"></select>

As you see now you need to create a new observable called selectedChoiceand we are going to populate that observable with the choice that is true using a computed.

正如您现在看到的,您需要创建一个名为的新 observable selectedChoice,我们将使用计算结果为 true 的选择填充该 observable。

var choices = [
    { id: 1, name: "one", choice: false },
    { id: 2, name: "two", choice: true },
    { id: 3, name: "three", choice: false }
    ];

function ViewModel(choices) {
   var self = this;
   self.choices = ko.observableArray(choices);
   self.trueChoice = ko.computed(function(){
       return ko.utils.arrayFirst(self.choices(), function(item){
           return item.choice === true;
       });
    });
    self.selectedChoice = ko.observable(self.trueChoice().id);
};

ko.applyBindings(new ViewModel(choices));

the new computed property trueChoiceuses the arrayFirstmethod in order to return the first item in your choices collection that has its choice property set to true.

新的计算属性trueChoice使用该arrayFirst方法返回choices 集合中第一个将choice 属性设置为true 的项目。

Now that we have our true choice all we have to do is to set the selected value of the dropdown aka selectedChoiceto be the id of that true choice so the item becomes selected in the drop down.

既然我们有了真正的选择,我们所要做的就是将下拉列表的选定值(又名)selectedChoice设置为该真实选择的 id,以便项目在下拉列表中被选中。

Here is also a working fiddle for this

这也是一个工作小提琴

回答by garryp

Added a Gist that disabled the first option in a select drop down list, and work nicely with KO's optionsCaptionbinding, using a optionsDisableDefaultbinding:

添加了禁用选择下拉列表中第一个选项的 Gist,并optionsCaption使用optionsDisableDefault绑定与 KO 的绑定很好地配合使用:

https://gist.github.com/garrypas/d2e72a54162787aca345e9ce35713f1f

https://gist.github.com/garrypas/d2e72a54162787aca345e9ce35713f1f

HTML:

HTML:

<select data-bind="value: MyValueField,
    options:OptionsList,
    optionsText: 'name',
    optionsValue: 'value',
    optionsCaption: 'Select an option',
    optionsDisableDefault: true">
</select>

回答by Morten

You could create a computed that holds the selected items

您可以创建一个计算来保存所选项目

self.selected_options = ko.computed({
    read: function() {
        return self.choices.filter(function(item){ return item.choice });
    },
    write: function(value) {
        self.choices.forEach(function(item) { item.choice = value.indexOf(item) > 0;});
    }
})

Then bind to that as the selected options.

然后绑定到它作为选定的选项。