2017-06-15 42 views
-3

這是我最初的js看起來像渲染HTML文件內容,並將其分配給對象

// template.js 
file: { 
    template : '<div><h2>Template</h2><p>My paragraph</p></div>'; 
} 

但我需要創建這個作爲一個單獨的HTML文件。

<!-- template.html --> 
<div> 
    <h2>Template</h2> 
    <p>My paragraph</p> 
</div> 

現在我需要導入並將其分配給腳本的對象(模板)。任何想法如何做到這一點?

// template.js 
file: { 
    template : 'Content Here'; 
} 
+0

使用Ajax加載文件? –

+0

你可以使用[.get()](https://api.jquery.com/jquery.get/) – Curiousdev

+0

你可以發佈一個嘗試嗎?你必須嘗試學習問是不夠的。 –

回答

1

您將不得不通過AJAX獲取它。這將是一個僞承諾(見:Promise$.get())與該文件的內容解析:

$.get(templateUrl).then(...) 

因此,一個很好的例子是:

// assuming `file` is inside `options` 
if (options.file.template == null && options.file.templateUrl != null) { 
    $.get(options.file.templateUrl).then(function(html) { 
    options.file.template = html 
    // continue doing stuff with the newly received html... 
    }); 
} 

注意我是如何把他們分開到templatetemplateUrl,但你不必這樣做。

注意:如果您嘗試使用promise的回調之外的結果,當您嘗試訪問它時(除非一段時間已過),您可能會得到undefined,因此您可能需要組織代碼以適應該。

相關問題