关于Knockout绑定的JQuery

时间:2014-08-06 18:37:14

标签: javascript jquery html knockout.js

我有一张桌子,上面有两个颜色。

问题:当我在文本框上尝试Jquery模糊事件时,它在第一行工作,但是当我添加新行时(将新行推送到可观察数组)。 blur事件对新行没有任何影响。

我正在使用Knockout.js

JQUERY

jQuery("#2CrpAcrs").blur(function () {
    var numb = $("#2CrpAcrs").val();
    numb = Math.round(numb * 100) / 100
    $("#2CrpAcrs").val(numb);
})

HTML

<tbody data-bind="foreach:Sec2">
                <tr>
                    <td>
                        <button class="btn btn-xs btn btn-danger" type="button" data-bind="click: $root.Sec2_RemoveRow">Remove</button>
                    </td>
                    <td>
                        <select class="form-control" data-bind="options: CrpType, value: CrpType,optionsValue:'value', optionsText:'crop'"></select>
                    </td>
                    <td>
                        <input id="2CrpAcrs" class="form-control" type="text" data-bind="value: NumAcres">
                    </td>
                </tr>
            </tbody>

2 个答案:

答案 0 :(得分:2)

编辑:请参阅下面的编辑。我建议重新考虑你的代码

你想用Knockout做这种事情的方式是使用自定义绑定处理程序:http://knockoutjs.com/documentation/custom-bindings.html

我想你会做这样的事情:

ko.bindingHandlers.yourBindingName = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
        $(element).blur(function () {
            var numb = $(this).val();
            numb = Math.round(numb * 100) / 100
            $(this).val(numb);
         });
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.
    }
};

然后在你的元素中你可以做这样的事情:

<input id="2CrpAcrs" class="form-control" type="text" data-bind="value: NumAcres, yourBindingName: {}">

此外,您当前的代码会导致多个具有相同ID的元素无效。考虑为2CrpAcrs使用类而不是ID。这可能是您当前问题的一部分。

编辑:

你为什么要使用jQuery?为什么不直接订阅您的价值观?这就是淘汰赛的目的。您可以订阅数据绑定到输入元素的任何内容,并对您想要的值进行任何自定义处理。

答案 1 :(得分:1)

.blur仅绑定到现有行。使用事件委托。

jQuery(document).on("blur", "#2CrpAcrs", function () {

顺便说一句,ID必须是唯一的,因此您不应使用#2CrpAcrs而是使用类。使用比document更具体的选择器(例如要添加行的表上的类或ID)也会更好。