我正在尝试在现有网页中自动填充一个我无法更改且该页面使用 Knockoutjs 的元素.输入元素或多或少看起来像这样:
<input maxlength="8" id="xxx" data-bind="textInput: otcInput" type="tel">
然后我使用 Knockoutjs尝试取消绑定(bind) textInput 并使用我需要的任何值动态填充输入元素,所以我这样做:
ko.cleanNode($('#xxx'));
ko.applyBindings({
otcInput: ko.observable("123") // populate myself
});
但是,这会导致错误 You cannot apply bindings multiple times to the same element
...问题是为什么?我已经在清理节点了……是不是?有没有一种方法可以使用 knockoutjs 查看在尝试执行我的“覆盖”ko.applyBindings
时是否存在悬挂绑定(bind)或剩余物?
我也尝试过其他方法通过 JQuery sendkeys plugin 设置输入值没有成功,即
$('#xxx').sendkeys('123'); // nothing happens
我也试过:
$('#xxx').unbind();
$('#xxx').off();
$('#xxx').sendkeys('123'); // but again nothing happens
最佳答案
您正在将一个 jQuery 对象传递给 cleanNode
。就像 applyBindings
一样,它必须是 DOM 元素,而不是 jQuery 对象。所以:
ko.cleanNode($('#xxx')[0]);
// -------------------^^^
示例——这失败了:
ko.applyBindings({
foo: ko.observable("one")
}, $("#test")[0]);
ko.cleanNode($("#test"));
ko.applyBindings({
foo: ko.observable("two")
}, $("#test")[0]);
<div id="test">
<div data-bind="text: foo"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
...但这(使用 [0]
)有效:
ko.applyBindings({
foo: ko.observable("one")
}, $("#test")[0]);
ko.cleanNode($("#test")[0]);
ko.applyBindings({
foo: ko.observable("two")
}, $("#test")[0]);
<div id="test">
<div data-bind="text: foo"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
I have also tried other ways to set the input value
如果那是您的目标,您不必处理绑定(bind)(这可能会产生不良影响),只需:
$("#xxx").val("new value").trigger("change");
trigger("change")
是让 KO 看到变化并更新 observable 所必需的。 (或者由于它是 textInput
绑定(bind),您可以使用 input
而不是 change
。)
示例——这失败了:
// The previously-bound stuff:
var vm = {
foo: ko.observable("foo")
};
ko.applyBindings(vm, document.body);
// Prove the observable and input are in sync:
console.log("check1", vm.foo(), $("#test").val());
// Update the field
$("#test").val("updated").trigger("change");
// Prove the observable and input are still in sync:
console.log("check2", vm.foo(), $("#test").val());
<input id="test" type="text" data-bind="textInput: foo">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
关于javascript - knockout 错误 : You cannot apply bindings multiple times to the same element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37497486/