挖空.js添加 Iframe 时数据绑定不起作用



我正在开发一个Web应用程序。我在客户端使用Knockout.js。

一切都很好,直到我添加一个iframe.iframedata-bind没问题,但外层停止工作。而且我无法单击按钮或在外页上执行任何操作。

这是我的主页:

<!DOCTYPE html>
<html>
<head>
  <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="knockout-3.4.2.js"></script>
  <script src="script.js"></script>
</head>
<body>
  username:
  <input data-bind="value: name" />
  <br /> age:
  <input type="text" data-bind="value: age" />
  <button data-bind="click: increase">Increase</button>
  <br />
  <button onclick="show()">show</button>
  <script>
    var show = function() {
      document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + '<div><iframe src="iframe.html" width="300" height="300"></iframe></div>';
    }
  </script>
</body>
</html>

这是它的模型:

$(document).ready(function() {
  function Outer(){
    var self = this;
    self.name = ko.observable("thomas");
    self.age = ko.observable(15);
    self.increase = function(){
      self.age(self.age() + 1);
    }
  }
  ko.applyBindings(new Outer());
});

在那里,我可以单击"增加"按钮来增加age值。但是当我点击显示显示iframe时,外页的数据消失了。

这是iframe及其模型:

$(document).ready(function() {
  function Inner(){
    var self = this;
    self.message = ko.observable("");
    self.text = ko.observable("begin");
    self.postData = function () {
      if (self.message().trim() !== '') {
        self.text(self.text() + "n" + self.message())
      }
      self.message('');
    }
  }
  ko.applyBindings(new Inner());
});

这是我在 Plunker 上的例子

您的show函数正在用新副本替换页面中的所有html。这些副本不再受 Knockout 的约束。相反,您应该以另一种方式添加<iframe>。例如,您可以使用淘汰!

<button data-bind="click: function() {showing(true)}">show</button>
<div data-bind="template: {name: 'iframe', if: showing}"></div>
<script type="text/html" id="iframe">
    <iframe src="iframe.html" width="300" height="300"></iframe>
</script>

最新更新