敲除绑定文本标签到下拉列表选择的选项文本 [英] knockout bind text label to dropdown value selected option text

查看:120
本文介绍了敲除绑定文本标签到下拉列表选择的选项文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来绑定一个div的文本框,以根据同一页面下拉菜单中所选选项的文本值进行更改?

Is there a simple way to bind the textbox of a div to change based on the text value of the selected option in a dropdown on the same page?

<div data-bind="text: dropdownValue"></div>
<select>
  <option value="1">Value1</option>
  <option value="2">Value2</option>
</select>

请注意,我不想使用javascript将值放入select元素。我想从HTML直接绑定值。我也可以包括jQuery来使其工作。

Please note, I don't want to put the values into the select element using javascript. I'd like to bind to the value straight from the HTML. I can also include jQuery to make it work.

推荐答案

我正在寻找类似的功能,我昨天在扔在一起的东西,没有找到它,所以我最终只是改变我在存储的价值属性。有时候,这是最简单的解决方案。

I was looking for similar functionality in something I was throwing together yesterday and couldn't find it, so I ended up just changing what I was storing in the value attributes. Sometimes that's the simplest solution.

这是一个使用jQuery的问题的一种快速而又难看的解决方案:

Here's a quick and kind of ugly solution to the problem using jQuery:

<div data-bind="text: dropdownText"></div>
<select data-bind="value: dropdownValue" id="dropdown">
  <option value="1">Value1</option>
  <option value="2">Value2</option>
</select>



JS



JS

function ViewModel() {
    var self = this;
    this.dropdownValue = ko.observable();
    this.dropdownText = ko.computed(function() {
        return $("#dropdown option[value='" + self.dropdownValue() + "']").text();
    });
};

ko.applyBindings(new ViewModel());

现场示例: http ://jsfiddle.net/5PkBF/

如果你想在多个地方这样做,最好写一个自定义绑定,例如:

If you were looking to do this in multiple places, it'd probably be best to write a custom binding, e.g.:

<div data-bind="text: dropdownValue"></div>
<select data-bind="selectedText: dropdownValue">
  <option value="1">Value1</option>
  <option value="2">Value2</option>
</select>



JS



JS

ko.bindingHandlers.selectedText = {
    init: function(element, valueAccessor) {
        var value = valueAccessor();
        value($("option:selected", element).text());

        $(element).change(function() {
            value($("option:selected", this).text());
        });
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $("option", element).filter(function(i, el) { return $(el).text() === value; }).prop("selected", "selected");
    }
};

function ViewModel() {
    this.dropdownValue = ko.observable();
};

ko.applyBindings(new ViewModel());

现场示例: http://jsfiddle.net/5PkBF/1/

这篇关于敲除绑定文本标签到下拉列表选择的选项文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆