在JavaScript文件中包含HTML的优雅简洁方法?

如何解决在JavaScript文件中包含HTML的优雅简洁方法?

| 我正在构建一个带有一些模式对话框窗口的小型应用程序。窗口需要一点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);
添加以澄清原始消息- 任何解决方案都不能使用Ajax / XHR来获取模板文件,因为javascript库将位于与其所包含的html文件不同的域中 有点像ShareThis。该库将包含在许多不同的站点上,并附加到div中具有属性sharetool = \“ true \”的任何锚点标记的onClick事件。 例如:
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>
    

解决方法

        模板。选择你的毒药 EJS jQuery模板(nb:开发已终止) 下划线模板 胡子 jResig微型模板 内联它们作为脚本块,或者使用ajax作为外部资源加载它们。 我个人使用EJS作为外部模板文件,只是让EJS加载它们并将它们注入到具有绑定到模板的json数据的容器中。
new EJS({ 
    url: \"url/to/view\"
}).update(\'html_container_name\',{
    \"foobar\": \"Suprise\"
});
然后,视图文件使用通用视图逻辑。
// url/to/view
<p> <%=foobar %></p>
    ,        您可以将HTML作为常规标记包含在页面末尾的不可见div中。然后,您可以使用jQuery引用它。 然后,您需要以编程方式设置变量字段(电子邮件,主题,正文)
<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>
    ,        对于多行字符串(没有框架,只有javascript),有几种解决方案。请参阅我对此SO问题的回答。您可以将其与一些简单的模板结合起来:
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=\"$0\"></div>\',\' <div><label for=\"subject\">Subject</label>\',\'      <input id=\"subject\" type=\"text\" disabled=\"disabled\" \',\'        value=\"$1\"></div>\',\' <div><label for=\"body\">Body</label>\',\'      <input id=\"body\" type=\"text\" disabled=\"disabled\" \',\'        value=\"$2\"></div>\',\' <div><input type=\"submit\" value=\"Send\"><input type=\"button\" \',\'        value=\"Cancel\" \',\'        onClick=\"javascript:$.fancybox.close();\"></div>\',\'</form>\'
  ] .join(\'\').template(email,subject,body);
    ,        您的问题有2个解决方案: -JavaScript中Heredoc语法的替代方法是使用
\\
转义换行符:
var tpl = \"hello\\
stackoverflow\\
World !\";
字符被转义,因此被忽略,并且它不会在结果字符串中发生。 您还可以使用模板创建一个普通的html文件,并在js脚本中创建一个隐藏的iframe并加载跨域html模板。现在,您可以访问iframe的文档对象并返回
body.innerHTML
。理论上!我尚未测试此解决方案。     ,        我个人喜欢这样构建DOM树:
$(\'#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
            )
        })
    )
);
    ,        您是对的,JS没有heredocs或多行字符串。也就是说,通常的做法是将HTML包含在HTML中,并在适当时显示或隐藏它。您已经在使用jQuery,所以您已经使用了大多数方法:
<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>
然后,您可以填充表单并将其扔到正确的位置:
$(\'#data\').html($(\'form.email\').find(\'input#from\').val(email).end().html());
    ,        Cook.js
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\'})
    ])
  ])
]);
怎么运行的
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\'})] 
进一步了解cook.js!     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?