简体   繁体   English

如何在html中重复代码而不必反复编写相同的代码

[英]How to repeat a code in html without writing the same code again and again

Well I wish to show a given piece of code multiple times on a given page but I wish to minimize the redundant code being repeated everywhere (simple copy/paste) . 好吧,我希望在给定的页面上多次显示给定的代码片段,但我希望尽量减少在任何地方重复的冗余代码(简单的复制/粘贴)。 Well I heard of people using Javascript or JQuery to store the given piece of code say HTML or CSS and than they use some simple div renders or the <!--data--> tag multiple number of times in wherever place they want the code to appear, which I have no idea how to use that is store a info in the scripts or html and then render it multiple number of places with a single div or comment. 好吧,我听说有人使用Javascript或JQuery来存储给定的代码片段,比如HTML或CSS,而不是他们在任何需要代码的地方多次使用一些简单的div渲染或<!--data-->标签出现,我不知道如何使用它是在脚本或HTML中存储信息,然后使用单个div或注释呈现多个位数。

Can anyone illustrate how to do this with an example. 任何人都可以举例说明如何做到这一点。 A bit more info on such tricks will be very resourceful. 关于这些技巧的更多信息将非常有用。

Have a look at server side includes 看一下服务器端包含的内容

Include it like this in your page : 在您的网页中包含以下内容:

<?php include ('content.html'); ?>

Here is simple JavaScript code to repeat text: (which can be modified as per requirement may be to insert innerHTML ) 以下是重复文本的简单JavaScript代码:(可根据要求修改,可插入innerHTML

function repeat(n,Txt){
    for(i=0; i<n;i++)
        document.write(Txt+ char(13)); //char(13) to draw new line
}

Just call this function as per requirement, on window.Load or onclick of a button.. 只需根据需要在window.Loadonclick按钮上调用此函数。

Update: Check this fiddle to Enter repeating HTML fiddle 更新:检查这个小提琴输入重复的HTML fiddle

Code for innerHTML: innerHTML代码:

function repeat(n,Txt){
    for(i=0; i<n;i++){
        document.getElementById("repeater").innerHTML = 
          document.getElementById("repeater").innerHTML + "<br /> "
           + Txt;
    }
}

An example of reusable code could look like the following (JavaScript example). 可重用代码的示例可能如下所示(JavaScript示例)。

var application = {
    addition: function (sum1, sum2) {
        return sum1 + sum2;
    },
    multiplication: function (sum1, sum2) {
        return sum1 * sum2;
    }
};

And you could call it as follows 你可以这样称呼它

application.addition(5, 10); /* returns 15 */

Or more complexly 或者更复杂

application.multiplicaton(application.addition(5, 10), 2) /* returns 30 */

Try Like 尝试喜欢

<!--#include virtual="/menu.shtml" -->

It will support by most of web servers. 它将支持大多数Web服务器。

More Info. 更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM