如何使用knockout js获取父表单id?

时间:2016-12-07 09:09:41

标签: javascript knockout.js

如何使用knockout js获取表单ID或表单类名?

<span data-bind="text: $parent.id"></span>

我想使用ko来到下面的位置以形成id或classname。

<form class="form-shipping-address" id="shipping-form" data-bind="attr: {'data-hasrequired': $t('* Required Fields')}">

    <div id="shipping-new-address-form" class="fieldset address">

        <div class="field _required" data-bind="visible: visible, attr: {'name': element.dataScope}, css: additionalClasses" name="shippingAddress.firstname">

            <label class="label" for="HV9JGHI">Firstname</label>

            <!-- I want to get here form id -->
            <span data-bind="text: $parent.id"></span>


            <input class="validate-length minimum-length-10 maximum-length-100" type="text" data-bind="
            value: value,
            valueUpdate: 'keyup',
            hasFocus: focused,
            attr: {
                name: inputName
            }" name="firstname"  id="HV9JGHI"> 
        </div>

    </div>
</form>

1 个答案:

答案 0 :(得分:1)

正如您可以在documentation on the binding context中看到的那样,$element变量可用,它链接到常规HTMLElement

您可以使用此parentElement

来使用此元素转到父级

&#13;
&#13;
ko.applyBindings({});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="parent-id">
  <div data-bind="text: $element.parentElement.id"></div>
</div>
&#13;
&#13;
&#13;

现在,如果您在父选择中需要更多逻辑,则可以使用与this answer中使用的辅助方法类似的辅助方法:

&#13;
&#13;
function closest(el, selector) {
  var matchesFn;

  // find vendor prefix
  ['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'].some(function(fn) {
    if (typeof document.body[fn] == 'function') {
      matchesFn = fn;
      return true;
    }
    return false;
  })

  var parent;

  // traverse parents
  while (el) {
    parent = el.parentElement;
    if (parent && parent[matchesFn](selector)) {
      return parent;
    }
    el = parent;
  }

  return null;
};

function closestFormId(el) {
  return (closest(el, "form") || {}).id;
}

ko.applyBindings({
  closestFormId: closestFormId
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<form id="form-id">
  <div id="parent-id">
    <div data-bind="text: closestFormId($element)"></div>
  </div>
</form>
&#13;
&#13;
&#13;

即使这样有效,我也无法想到你想要这样做的原因......为什么不在你的viewmodel中创建一个id属性并使用它来代替(通过{ {1}})?