在 JavaScript 文件中包含 HTML 的优雅干净的方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6192268/
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-08-23 20:39:54  来源:igfitidea点击:

Elegant clean way to include HTML in JavaScript files?

javascriptjquery

提问by Andrew Hopper

I'm building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I've hard coded the window HTML in the javascript library but am not thrilled with this solution. Is there a more elegant way to do this? It seems that JavaScript doesn't have multi line strings/heredoc syntax.

我正在构建一个带有几个模态对话框窗口的小应用程序。这些窗口需要一点点 HTML。我已经在 javascript 库中对窗口 HTML 进行了硬编码,但对这个解决方案并不感到兴奋。有没有更优雅的方法来做到这一点?JavaScript 似乎没有多行字符串/heredoc 语法。

var html = "<div id='email_window'><h2>Email Share</h2><div>";
html = html + "<form action='javascript:emailDone();' method='post'>";
html = html + "<div><label for='to'>To</label><input id='to' type='text'></div>";
html = html + "<div><label for='from'>From</label><input id='from' type='text' value='" + email + "'></div>";
html = html + "<div><label for='subject'>Subject</label><input id='subject' type='text' disabled='disabled' value='" + subject + "'></div>";
html = html + "<div><label for='body'>Body</label><input id='body' type='text' disabled='disabled' value='" + body + "'></div>";
html = html + "<div><input type='submit' value='Send'><input type='button' value='Cancel' onClick='javascript:$.fancybox.close();'></div>";
html = html + "</form></div>";

$("#data").html(html);

Added to clarify the original message-

添加以澄清原始消息-

Any solution can't use Ajax/XHR to pull in the template file because the javascript library will be on a different domain that the html file it's included in It's a little like ShareThis. The library will be included on a number of different sites and attached to the onClick event of any anchor tag inside divs with attribute sharetool="true".

任何解决方案都不能使用 Ajax/XHR 来拉入模板文件,因为 javascript 库将位于与它所包含的 html 文件不同的域上,这有点像 ShareThis。该库将包含在许多不同的站点中,并附加到属性 sharetool="true" 的 div 内任何锚标记的 onClick 事件。

For example:

例如:

http://www.bar.com - index.html
<html>
...
<script type="text/javascript" src="http://www.foo.com/sharetool.js"></script>
...
<body>
<div sharetool="true">
</div>
...
</html>

采纳答案by Raynos

Templates. Pick your poison

模板。选择你的毒药

Either inline them as script blocks or load them using ajax as external resources.

要么将它们内联为脚本块,要么使用 ajax 作为外部资源加载它们。

I personally use EJS as external template files and just get EJS to load them and inject them into a container with json data bound to the template.

我个人使用 EJS 作为外部模板文件,只是让 EJS 加载它们并将它们注入到容器中,并将 json 数据绑定到模板。

new EJS({ 
    url: "url/to/view"
}).update('html_container_name', {
    "foobar": "Suprise"
});

And then view files use generic view logic.

然后视图文件使用通用视图逻辑。

// url/to/view
<p> <%=foobar %></p>

回答by Michael Berkowski

You can include the HTML as regular markup at the end of the page, inside an invisible div. Then you're able to reference it with jQuery.

您可以将 HTML 作为常规标记包含在页面末尾的不可见 div 中。然后你就可以用 jQuery 引用它了。

You then need to programmatically set your variable fields (email, subject, body)

然后,您需要以编程方式设置变量字段(电子邮件、主题、正文)

<div id='container' style='display: none;'>
  <div id='your-dialog-box-contents'>
    ...
    ...
  </div>
</div>

<script type='text/javascript'>
  $("#from").val(from);
  $("#subject").val(subject);
  $("#body").val(body);
  $("#data").html($("#your-dialog-box-contents"));
</script>

回答by KooiInc

For multiline strings (no frameworks, just javascript) there are several solutions. See my answer to this SO Question. You could combine that with some simple templating:

对于多行字符串(没有框架,只有 javascript),有几种解决方案。请参阅我对此问题的回答。您可以将其与一些简单的模板结合起来:

String.prototype.template = String.prototype.template ||
        function (){
            var  args = Array.prototype.slice.call(arguments)
                ,str = this
                ,i=0
                ;
            function replacer(a){
                var aa = parseInt(a.substr(1),10)-1;
                return args[aa];
            }
            return  str.replace(/($\d+)/gm,replacer)
};
//basic usage:
'some #1'.template('string'); //=> some string
//your 'html' could look like:
var html =
  [ '<form action="javascript:emailDone();" method="post">',
    ' <div><label for="to">To</label>',
    '       <input id="to" type="text"></div>',
    ' <div><label for="from">From</label>',
    '       <input id="from" type="text" ',
    '         value="
var tpl = "hello\
stackoverflow\
World !";
"></div>', ' <div><label for="subject">Subject</label>', ' <input id="subject" type="text" disabled="disabled" ', ' value=""></div>', ' <div><label for="body">Body</label>', ' <input id="body" type="text" disabled="disabled" ', ' value=""></div>', ' <div><input type="submit" value="Send"><input type="button" ', ' value="Cancel" ', ' onClick="javascript:$.fancybox.close();"></div>', '</form>' ] .join('').template(email, subject, body);

回答by Dev in Gfx

There is 2 solutions tto your problem: - An alternative to the heredoc Syntax in javascript is to escape the newline char with \:

有 2 种解决方案可以解决您的问题: - javascript 中 heredoc 语法的替代方法是使用以下方法转义换行符\

$('#data').html(
    $('<div/>', {
        id: 'email_window',
        html: $('<h2/>', {
            html: 'Email Share'
        })
    }).after(
        $('<form/>', {
            action: 'javascript:emailDone();',
            method: 'post',
            html: $('<div/>', {
                html: $('<label/>', {
                    for: 'to',
                    html: 'To'
                }).after($('<input/>', {
                    id: 'to',
                    type: 'text'
                }))
            }).after(
                ... etc
            )
        })
    )
);

The char is escaped so ignored, and it wont take place in the resulting string.

字符被转义,因此被忽略,它不会出现在结果字符串中。

You can also create a plain html file with your template, and in your js script you create a hidden iframe and load the crossdomain html template. You can now access the document object of the iframe and retreive body.innerHTML. In theory! I Didn't tested this solution yet....

您还可以使用模板创建一个纯 html 文件,并在您的 js 脚本中创建一个隐藏的 iframe 并加载跨域 html 模板。您现在可以访问 iframe 的文档对象并检索body.innerHTML。理论上!我还没有测试过这个解决方案......

回答by Darin Dimitrov

Personally I like building DOM trees like this:

我个人喜欢像这样构建 DOM 树:

<div style="display:none;">
    <form method='post' class="email">
         <input id='from' type='text'> <!-- other form fields omitted for brevity -->
    </form>
    <form method='post' class="facebook"></form> <!-- again, omitted for brevity -->
</div>

回答by Dan Davies Brackett

You're right, JS doesn't have heredocs or multi-line strings. That said, the usual approach to this is to have the HTML in...the HTML, and show or hide it as appropriate. You're already using jQuery, so you're most of the way there:

你是对的,JS 没有heredocs 或多行字符串。也就是说,通常的方法是将 HTML 放入...HTML,并根据需要显示或隐藏它。您已经在使用 jQuery,所以您已经完成了大部分工作:

$('#data').html($('form.email').find('input#from').val(email).end().html());

Then, you can populate the form and toss it in the right spot:

然后,您可以填充表单并将其扔到正确的位置:

div([
  button({click:[firstEvent, secondEvent]},
         'You can bind (attach) events on the fly.'),
  p('Here are some popular search engines'),
  ul([
    li([
      a('Google', {href:'http://www.google.com'})
    ]),
    li([
      a('Bing', {href:'http://www.bing.com'})
    ]),
    li([
      a('Yahoo', {href:'http://www.yahoo.com'})
    ])
  ])
]);

回答by Raj Nathani

Cook.js

库克.js

Objects = Attribute & Events
    -> {href:'facebook.com', src:'static/cat.gif', ng-bind:'blah'}
String  = Text or Html
    -> 'hello world'
Array   = Elements
    -> [a('hello world', {href:'facebook.com'}), img({src:'static/cat.gif'})] 

how it works

这个怎么运作

##代码##

more on cook.js!

更多关于cook.js!