2014-04-01 24 views
0

未定義index.html中的index.js骨幹this.el在本地

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="utf-8"> 
    <title>hello-backbonejs</title> 
    <script src="js/jquery.js"></script> 
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> 
     <script src="js/underscore.js"></script> 
    <script src="js/backbone.js"></script> 
    <script src="js/app/index.js"></script> 
    </head> 
    <body></body> 
    </html> 

(function($){ 
    // **ListView class**: Our main app view. 
    var ListView = Backbone.View.extend({ 
     el: $('body'), // attaches `this.el` to an existing element. 
     // `initialize()`: Automatically called upon instantiation. Where you make all types of bindings, _excluding_ UI events, such as clicks, etc. 
initialize: function(){ 
     _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods 
     console.log(this); 
     this.render(); // not all views are self-rendering. This one is. 
     }, 
     // `render()`: Function in charge of rendering the entire view in `this.el`. Needs to be manually called by the user. 
     render: function(){ 
    console.log(this); 
     $(this.el).append("<ul> <li>hello world</li> </ul>"); 
     } 
    }); 

    // **listView instance**: Instantiate main app view. 
    var listView = new ListView(); 
    })(jQuery); 

,如果我訪問此通過file:/// C:/用戶在/ usr/Desktop/backbone/index.html,this.el未定義。爲什麼?

如果我複製粘貼相同的代碼在jsfiddle其工作。不知道爲什麼enter image description here

回答

4

您的JavaScript代碼正在您的html文檔中存在的body標籤之前執行。直接在結束標記之前把你的腳本標籤,就像這樣:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>hello-backbonejs</title> 
</head> 
<body> 
<!-- content here --> 

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script> 
<script src="js/app/index.js"></script> 
</body> 
</html> 

我測試了這一點,它爲我的作品與你的JavaScript文件

+1

你也可以替換'EL:$(「身體」)'與'el:'身體''(無論如何IMO都好得多)。 –

+0

確實,你可以做到這一點,而且這是一個更好的方式,但這不是問題。我改變他的代碼來閱讀你描述的方式,問題依然存在 –