javascript 自定义或可重用的 HTML 组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16327622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:13:14  来源:igfitidea点击:

Custom or Reusable HTML component

javascripthtml

提问by Kiran Nunna

Can we create custom or reusable components in HTML?

我们可以在 HTML 中创建自定义或可重用的组件吗?

My page has account search functionality which is implemented using HTML, JS, jQuery code. And my page consists of account search at different places. (Functionality is same tough). Only ID of the div changes at each time we using it.

我的页面具有使用 HTML、JS、jQuery 代码实现的帐户搜索功能。我的页面由不同地方的帐户搜索组成。(功能同样强大)。每次我们使用它时,只有 div 的 ID 会发生变化。

So can we come up with kind of components in HTML?

那么我们可以在 HTML 中想出一些组件吗?

Again, Writing the code in separate file and including at different locations wont work as ID changes at each area. ID matter as we make call to server, get data and update the fields etc.

同样,在单独的文件中编写代码并包含在不同的位置将不会在每个区域的 ID 更改时起作用。当我们调用服务器、获取数据和更新字段等时,ID 很重要。

采纳答案by Kiran Nunna

Following frameworks helps to solve the problem:

以下框架有助于解决问题:

Mustache

胡子

HandleBars

车把

I prefer to use HandleBar (which is written on top of Mustache).

我更喜欢使用 HandleBar(写在 Mustache 之上)。

回答by George Reith

Look into javascript templating. See mustache.jsfor one example.

查看javascript模板。参见mustache.js的一个例子。

e.g.

例如

<script type="text/template" id="template">
   {{#elements}}
      <div id="{{id}}">
         {{content}}
      </div>
   {{/elements}}
</script>

And your JavaScript:

还有你的 JavaScript:

var view = {
   "elements": 
    [
       {
          id: "one",
          content: "Lorem ipsum dolor"
       },
       {
          id: "two",
          content: "Sit amet consectetur"
       }
    ]
}

var template = document.getElementById("template").innerHTML;
var output = Mustache.render(template, view);
console.log(output);

logs:

日志:

<div id="one">
   Lorem ipsum dolor
</div>
<div id="two">
   Sit amet consectetur
</div>

You can loop through objects, evaluate functions and insert them as text.

您可以遍历对象、评估函数并将它们作为文本插入。

回答by fotanus

HTML is a markup language, not a programming language. Most likely you are looking for a template enginelike haml

HTML 是一种标记语言,而不是一种编程语言。您很可能正在寻找像haml这样的模板引擎

回答by Stan

If you use angularJS you can create a reusable html piece by making a separate html file with your component then calling it into your page as an element.

如果您使用 angularJS,您可以通过使用您的组件创建一个单独的 html 文件,然后将其作为元素调用到您的页面中来创建一个可重用的 html 片段。

app.directive("elementName", function() {
  return {
    restrict: 'E',
    templateUrl: "/Path/To/Html.file"
  };
});

Then in every html page you want to use this component you just do the following:

然后在您想要使用此组件的每个 html 页面中,您只需执行以下操作:

<element-name></element-name>

回答by Wanderson Silva

Actually maybe you could use the separate js file, the implementation just needs to receive (maybe in the constructor, or if not a class, look up for a specific html tag) and use that required information when needed.

实际上,也许您可​​以使用单独的 js 文件,实现只需要接收(可能在构造函数中,或者如果不是类,则查找特定的 html 标记)并在需要时使用所需的信息。

回答by dandavis

i love a good template engine, but you can use simple markup to decouple your logic from the html controls.

我喜欢一个好的模板引擎,但是您可以使用简单的标记将您的逻辑与 html 控件分离。

bootstrap does this using classes, and data- attributes work as well for more precise control.

bootstrap 使用类来做到这一点,并且数据属性也可以用于更精确的控制。

you need to cleanup your code slightly; gather all the code you need, and detach all the refs to any given id. Usually, this is not difficult because you only have one or two spots that use the id, performing the rest of your operations using a variable.

你需要稍微清理一下你的代码;收集您需要的所有代码,并将所有引用分离到任何给定的 id。通常,这并不困难,因为您只有一两个点使用 id,使用变量执行其余操作。

wrap up all the code into one function that takes an element for it's only argument; this was formerly the one hard-coded to the id. move any IDs used in the code to classes or better yet, variables. change the css to reflect these classes and/or descendants of the widget class (more soon). at this point, you should be able to call the function and pass an element, and have it work. let's call it makeSearchFromElement().

将所有代码包装到一个函数中,该函数接受一个元素作为它的唯一参数;这以前是硬编码到 id 的那个。将代码中使用的任何 ID 移到类或更好的变量中。更改 css 以反映这些类和/或小部件类的后代(更多)。此时,您应该能够调用该函数并传递一个元素,并使其工作。我们称之为 makeSearchFromElement()。

function makeSearchFromElement(elm){
  elm.onchange=function(e){ alert("searching for " + elm.value); };
}

once you can do that, all you need is an easy way to define them. let's use a class of "widget-search" as an example. add the class to any html element that needs the search functionality in your package.

一旦你能做到这一点,你所需要的就是一种简单的方法来定义它们。让我们以“widget-search”类为例。将该类添加到包中需要搜索功能的任何 html 元素中。

<input class='search widget-search validation' id=search123 type=search />

now, all you have to do is find all the declared widgets in the HTML and send them to the widget maker somewhere in a site-wide JS file :

现在,您所要做的就是在 HTML 中找到所有声明的小部件,并将它们发送到站点范围 JS 文件中某个位置的小部件制造商:

[].slice
  .call(document.getElementsByClassName("widget-search"))
  .map(makeSearchFromElement);

if you don't inject at the bottom of the body tag, you'll want to place that last bit in a ready() or onload() event.

如果您不在 body 标记的底部注入,您需要将最后一位放在 ready() 或 onload() 事件中。

that's all you need to do to enable any input to have the demo "search" ability simply by adding a class to the HTML, not a single line of CSS or JS needed to add each one. It lets you patch or upgrade each one on the site from one spot, and it reduces the amound of custom code to be shipped over the wire, making the page load faster than hand-binding or even template-ing them.

这就是您只需将一个类添加到 HTML 即可使任何输入具有演示“搜索”功能所需要做的一切,而不是添加一行所需的 CSS 或 JS 行。它让您可以从一个位置修补或升级站点上的每一个,并且它减少了通过网络传送的大量自定义代码,使页面加载速度比手动绑定甚至模板化它们更快。

回答by user10

Refer this blog post. It elaborates "how to create reusable components" using Handlebar.js. Definitely worth reading it.

请参阅此博客文章。它详细说明了“如何使用 Handlebar.js 创建可重用组件”。绝对值得一读。

Below code is enough to add datetimepicker in your app.

下面的代码足以在您的应用程序中添加 datetimepicker。

{{datetime "d1" "Start Date"}}

jsFiddle for this

jsFiddle为此