【问题标题】:Access jQuery Object from inside a custom binding handler从自定义绑定处理程序内部访问 jQuery 对象
【发布时间】:2015-07-28 17:33:49
【问题描述】:

我正在尝试访问一个 jQuery 对象,它恰好是一个输入文本框,用于进行一些验证和添加日期选择器,但不幸的是我无法这样做。

我正在使用 KnockoutJS。

如果“数据类型”恰好是“日期”或“日期时间”,我想访问“输入”并在其上调用 datepicker()。但是每当我尝试使用.closest('td').next('td').html() 进行搜索时,我都会得到一个空值(来自自定义绑定内部)。尝试这样做,以便我可以根据数据类型“td”在输入上调用 datetimepicker 构造函数。

下面是我正在尝试使用的小提琴

JsFiddle:http://jsfiddle.net/sourabhtewari/nkkt88v2/2/

   var format = function (str, col) {
    col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);

    return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
        if (m == "{{") {
            return "{";
        }
        if (m == "}}") {
            return "}";
        }
        return col[n];
    });
};

var data = ko.observableArray([{
    paramKey: ko.observable('keyName'),
    paramValue: ko.observable('Test1'),
    dataType: ko.observable('Date')
}]);


var ParamConstr = function (key, value, dataType) {
    return {
        ParamKey: ko.observable(key),
        ParamValue: ko.observable(value),
        DataType: ko.observable(dataType)

    };
};
var my = my || {};
function Generator() { };

Generator.prototype.rand = Math.floor(Math.random() * 26) + Date.now();

Generator.prototype.getId = function () {
    return this.rand++;
};
var idGen = new Generator();
//var ParamData = ko.observableArray([]);
my.viewModel = {
    ParamData : ko.observableArray([]),
    addParam: function () {
         this.ParamData.push(new ParamConstr("$$" + "key1", "value1","Date"));
    }};

ko.bindingHandlers.hidden = {
    update: function (element, valueAccessor) {
        ko.bindingHandlers.visible.update(element, function () { return !ko.utils.unwrapObservable(valueAccessor()); });
    }
};


ko.bindingHandlers.clickToEdit = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {

        var observable = valueAccessor(),
            link = document.createElement("a"),
            input = document.createElement("input");

        var id = idGen.getId();
        input.setAttribute("id", id);

        element.appendChild(link);
        element.appendChild(input);


        console.log(document.getElementById(id).id);

        var dataType = $(format("#{0}", id)).parent().next('td').html();
        //.parent().next().html();
        //.closest('td').next('td').html().toString();
        console.log(dataType);

        switch ($(format("#{0}", id)).parent().next('td').html()) {

            case "Datetime":
                $(format("#{0}", id)).datetimepicker();
                break;

            case "Date":
                $(format("#{0}", id)).datetimepicker({
                    timepicker: false,
                    format: 'Y/m/d'
                });
                break;
        }

        observable.editing = ko.observable(false);

        ko.applyBindingsToNode(link, {
            text: observable,
            hidden: observable.editing,
            click: observable.editing.bind(null, true)
        });

        ko.applyBindingsToNode(input, {
            value: observable,
            visible: observable.editing,
            hasfocus: observable.editing,
            event: {
                keyup: function (data, event) {
                    //if user hits enter, set editing to false, which makes field lose focus
                    if (event.keyCode === 13) {
                        input.blur();
                        observable.editing(false);
                        return false;
                    }
                    //if user hits escape, push the current observable value back to the field, then set editing to false
                    else if (event.keyCode === 27) {
                        observable.valueHasMutated();
                        observable.editing(false);
                        return false;
                    }

                }
            }
        });
    }
};

ko.applyBindings(my.viewModel);

html:

<div>
    <button id="InputSubmitBtn" type="submit" class="btn btn-custom" data-bind="click: addParam"><span class="glyphicon glyphicon-plus-sign"></span>&nbsp;Add</button>
</div>
<table class="table table-hover table-condensed">
    <thead>
        <tr>
            <th>Name</th>
            <th>Value</th>
            <th>Data type</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: ParamData">
        <tr>
            <td data-bind="text: ParamKey" style="width: 20%"></td>
            <td data-bind="clickToEdit: ParamValue" data-text="" style="width: 20%"></td>
            <td data-bind="text: DataType" style="width: 20%"></td>
        </tr>
    </tbody>
</table>

任何关于我如何解决这个问题的帮助都会很棒!

【问题讨论】:

  • 如果您的目标是获取数据类型,那么您可以使用 allbindingaccessors 参数来实现它。将您的 html 修改为 并在您的自定义绑定中添加以下行为您提供数据类型 var dataType = allBindingsAccessor().datatype(); console.log(allBindingsAccessor().datatype());。您可以将其用作切换大小写的输入,以与所需的数据类型进行比较。检查它,让我们知道它是否有效
  • 完成了这项工作。谢谢。
  • 很高兴听到它有效。快乐编码

标签: javascript jquery knockout.js


【解决方案1】:

看来你从 G_S 那里得到了答案。

如果有人想知道什么是正确的选择器,var dataType = $(element).next().text(); 可以完美地完成这项工作。您无法访问任何数据,因为在通话时它还不存在。你可以试试var dataType = $(element).prev().text();,看看你能找回$$key1。

Fiddle

无论如何,正如你得到的回答,我没有进一步探讨如何解决这个问题,祝你有美好的一天:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2023-04-08
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多