2

I'm trying to use knockout and jquerymobile and can't get it to work. Here's my code:

<!DOCTYPE html>     
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="/nw/scripts/jquery-1.8.2.js"></script>
    <script src="/nw/scripts/knockout-2.1.0.debug.js"></script>
    <script src="/nw/scripts/jquery.mobile-1.2.0.js"></script>
    <link rel="stylesheet" href="/nw/scripts/jquery.mobile-1.2.0.css" />
        <title>title</title>
</head>
    <body>
        <div>
<script type="text/javascript">
    function AppViewModel() {
        this.test = [{ "name": "noam", "age": "36" }, { "name": "yael", "age": "34"}];
    }
    $(document).ready(function () { 
        ko.applyBindings(AppViewModel());
        });
</script>
<ul data-bind="foreach: test" id="myList">
    <li>test <span data-bind="text: name"></span></li>
</ul>
        </div>
    </body>
</html>

When I run this I get the following error: Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

When I comment out the jquerymobile scripts, it works.

Any help would be appriciated

4

1 回答 1

0

问题的直接原因是调用<script>块的位置。ko.applyBindings如果您将<script>块移动到<head>标签中,该示例将按原样工作,如下所示:(另请注意pageinit事件和data-role="page"属性的使用)

<!DOCTYPE html>     
<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
  <script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.debug.js"></script>
  <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
  <title>title</title>
  <script type="text/javascript">
    function AppViewModel() {
      this.test = [{ "name": "noam", "age": "36" }, { "name": "yael", "age": "34"}];
    }
    $(document).bind('pageinit', function () {
      ko.applyBindings(AppViewModel());
    });
  </script>
</head>
  <body>
    <div data-role="page">
      <ul data-bind="foreach: test" id="myList">
        <li>test <span data-bind="text: name"></span></li>
      </ul>
    </div>
  </body>
</html>

请记住,jquery mobile 和 knockout 都会更改 DOM,并且 DOM 错误是它们之间冲突的征兆,其中一个库移动了另一个库随后试图解决的 DOM 元素。

为了让 JQM 和 knockout 一起工作(它们确实如此),您需要非常熟悉 JQM 何时/如何对 DOM 进行更改。这个页面可能是一个很好的起点。

于 2012-11-17T08:27:09.787 回答