重用HTML的元素

Jod*_*ell 7 html javascript jquery html5

我正在编写一个静态网站,它使用JQuery对RESTful API进行一些AJAX调用,并使用数据填充页面.

网站功能正常(并且很快),一切都很好.

当我扩展网站并添加其他页面时,我注意到我在每个页面上都复制了某些区域.

例如,每个页面共享一个共同的header元素.

<header>...Some non-trivial content...</header>
Run Code Online (Sandbox Code Playgroud)

不是在每个页面上重复这个定义,而是有一些机制,通过这个机制,我可以定义此部分一次并将其包含在每个文档中.

请记住,必须静态提供页面,但可以使用任何标准的投诉浏览器功能.

有没有一个很好的方法来做到这一点,它是什么,或者,我将不得不放弃我的客户端代码的这方面的DRY原则

pla*_*alx 6

肯定有一些方法可以实现这一目标。您可以使用服务器端语言的某些功能(允许在另一个页面中包含页面的内容)来完成此操作,或者,如果您没有任何服务器端技术,则可以将该代码放入自己的html文档中并使用AJAX加载内容。

在jQuery中,它可能看起来像:

$('#header').load('header.html');
Run Code Online (Sandbox Code Playgroud)

但是,如果并非所有页面的内容都是静态的,则始终可以定义一个JS模块来呈现此标头。您的模块可以使用客户端模板引擎,例如MustacheHandlebars等。但是,您不必使用任何这些引擎。

这是一个简单的例子:

演示

//in somefile.js, please note that you should namespace your modules
var Header = {
    //default config
    config: {
        el: '#header',
        title: 'Some title'
    },

    init: function (config) {
        var cfg = this.config = $.extend({}, this.config, config);

        $(cfg.el).html('<h1>' + cfg.title + '</h1>');
    }
};

$(function () {
    Object.create(Header).init({
        title: 'Some other title'
    });

    Object.create(Header).init({
        el: '#header1',
        title: 'Yeah'
    });
});
Run Code Online (Sandbox Code Playgroud)


Joh*_*han 5

正如我在评论中提到的,这就是我的方法:

main.html

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Main page</title>
        <sript src="http://code.jquery.com/jquery-latest.js"></script>
        <script>
             $(function(){
                  $('#commonsection').load('reusablefile.htm');

                  // which is eqvivalent to:
                  //
                  // $.ajax({
                  //     url: 'reusablefile.htm',
                  //     dataType: 'html',
                  //     success: function(data){
                  //         $('#commonsection').html(data);
                  //     }
                  // });
             });
        </script>
     </head>
     <body>
         <div id="commonsection"></div>
     </body>
</html>
Run Code Online (Sandbox Code Playgroud)

reusablefile.html:

<script>
    (function($){ //separate scope to keep everything "private" for each module
        //do additional javascript if required
    })(jQuery);
</script>
<p>...Some non-trivial content...</p>
Run Code Online (Sandbox Code Playgroud)