如何优雅的用js动态添加html代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何优雅的用js动态添加html代码相关的知识,希望对你有一定的参考价值。

一、使用javascript 模板引擎
用javascript预编译模版,就是动态修改模板文件使之成为一个可用的静态html文件。 我平时会使用artTemplate,性能很好而且易上手。
编写模板
使用一个type="text/html"的script标签存放模板:

<script id="test" type="text/html">
<h1>title</h1>
<ul>
each list as value i
<li>索引 i + 1 :value</li>
/each
</ul>
</script>

渲染模板
var data =
title: \'标签\',
list: [\'文艺\', \'博客\', \'摄影\', \'电影\', \'民谣\', \'旅行\', \'吉他\']
;
var html = template(\'test\', data);
document.getElementById(\'content\').innerHTML = html;
二、使用CoffeeScript
CoffeeScript支持类似于Python的跨行字符串,这样很轻易的就能保持HTML结构的可读性,而不需要使用“+”或者采用拼数组的形式。

str="""
<div class="dialog">
<div class="title">
<img src="close.gif" />关闭
</div>
<div class="content">
<img src="delete.jpg" />
</div>
<div class="bottom">
<input id="Button2" type="button" value="确定" class="btn"/>
<input id="Button3" type="button" value="取消" class="btn"/>
</div>
</div>
"""
参考技术A 动态添加html代码很容易,但是优雅……这就难了,以为每个人理解的“优雅”不一样

JS动态添加删除html

本功能要求是页面传一个List 集合给后台而且页面可以动态添加删除html代码需求如下:

下面是jsp页面代码

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="m" uri="/my-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/coder" prefix="coder"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="cache-control" content="no-cache">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" name="viewport" id="viewport">

<title>店铺设置</title>
<%@include file="/res/funcanteen/businessheadinclude.jsp"%>
<link rel="stylesheet" href="<%=basePath%>res/funcanteen/css/jquery-weui.css">

<script type="text/javascript" src="<%=basePath%>res/funcanteen/js/jquery-2.0.0.min.js"></script>
<script type="text/javascript" src="<%=basePath%>res/funcanteen/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>res/funcanteen/js/jquery-weui.js"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>
    <form id="form" action="" method="post">
    <input type="hidden" id="stallId" name="stallId" value="${stallId }">
    <input type="hidden" id="timeType" name="timeType" value="${timeType }">
    
<div id="box">
    <!--头部-->
    <div class="header">
        <a href="<%=basePath%>book/business/version2/store?stallId=${stallId}" class="back"></a>营业时间
    </div>
    <!--中间内容区域-->
    <div class="store_cent" style="">
        <ul class="have_int">
                <ul class="time_dtn" id="afternoonTeaScanTime">
                    <li style="border-top:1px solid #c9c9c9;">
                       <div class="date all_activity">
                       <c:choose>
                          <c:when test="${businessList !=null  && businessList.size() >0}">
                             <c:forEach items="${businessList }" var="business" begin="0" varStatus="status">
                              <c:set var="num" value="${status.count-1}"></c:set>
                              <input type="hidden" value="${business.id }" name="stallTimeList[${num}].id">
                               <input type="hidden" value="${business.stallId }" name="stallTimeList[${num}].stallId">
                               
                               <div class="activity_class">
                                <span class="set_leftd" style="width: 10%;"><img src="<%=basePath%>res/funcanteen/images/Business/list_bg12.png" alt=""></span>
                                <div class="set_rightd" style="width: 90%;">
                                    <input type="text" readOnly="true" style="width: 38%;" id="stallTimeList[${num}].start" name="stallTimeList[${num}].start" value="${business.start }" class="business stallTime_start">
                                    <span style="width: 5%;"></span>
                                    <input type="text" readOnly="true" style="width: 38%;" id="stallTimeList[${num}].end" name="stallTimeList[${num}].end" value="${business.end }" class="business stallTime_end">
                                    <div class="dell_all" stallTimeId="${business.id }">
                                    <span style="width: 10%;" class="title_name dell_coupon">删除</span><span style="width: 7%;" class="konck_icon konck_i"></span>
                                    </div>
                                </div>
                               </div>
                           </c:forEach>
                          </c:when>
                          <c:otherwise>
                             <div class="activity_class">
                                <span class="set_leftd" style="width: 10%;"><img src="<%=basePath%>res/funcanteen/images/Business/list_bg12.png" alt=""></span>
                                <div class="set_rightd" style="width: 90%;">
                                    <input type="text" readOnly="true" style="width: 38%;" id="stallTimeList[0].start"  name="stallTimeList[0].start" value="" class="business stallTime_start">
                                    <span style="width: 5%;"></span>
                                    <input type="text" readOnly="true" style="width: 38%;" id="stallTimeList[0].end"  name="stallTimeList[0].end"value="" class="business stallTime_end">
                                    <div class="dell_all" >
                                    <span style="width: 10%;" class="title_name dell_coupon">删除</span><span style="width: 7%;" class="konck_icon konck_i"></span>
                                    </div>
                                </div>
                               </div>
                          </c:otherwise>
                       </c:choose>
                       </div>
                       <div class="activity_add" style="float: right;">
                           <span class="title_name add_coupon">添加时间</span>
                           <span class="konck_icon konck_h"></span>
                       </div>
                    </li>
                </ul>
        </ul>
    </div>
    <!--底部-->
    <div class="store_d">
        <button type="button" id="subUpdate">保存</button>
    </div>
</div>
</form>
<script>
    $(function(){
        $("#subUpdate").click(function() {
            //判断所有的时间必须填
            var flag=false;//判断配置时间必须填
            var dateSize=false;//判断开始时间不能大于结束时间
            $(".activity_class").each(function (){
                var start = $(this).find(".stallTime_start").val();
                var end = $(this).find(".stallTime_end").val();
                if(start==null || start==""){
                    flag=true;
                    return false;
                }
                if(end==null || end==""){
                    flag=true;
                    return false;
                }
                if(start >= end){
                    dateSize=true;
                    return false;
                }
            });
            if(flag){
                alert(\'配置时间必须填\');
                return;
            }
            if(dateSize){
                alert("开始时间不能大于结束时间");
                return;
            }
            $.ajax({
                url : "<%=basePath %>book/business/version2/store!saveUpdateStallTime",
                data : $("#form").serialize(),
                type : "POST",
                success : function(data) {
                    if(data.success){
                        window.location.reload()
                    }
                }
            });
        });
    })
</script>
<script>
    $(function(){ 
      $(".set_rightd input[type=\'text\']").picker({
        title: "设置时间",
        cols: [
          {
            textAlign: \'right\',
            values: (function () {
                var hours = [];
                for (var i=0; i<24; i++) hours.push(i > 9 ? i : \'0\'+i);
                return hours;
              })()
          },
          { 
              textAlign: \'center\',
            values: [\':\']
          },
          {
            textAlign: \'left\',
            values: (function () {
                var minutes = [];
                for (var i=0; i<60; i++) minutes.push(i > 9 ? i : \'0\'+i);
                return minutes;
              })()
          }
        ]
      });
    //删除营业时间配置
       $(\'.dell_coupon\').click(function(){ 
          delFcuk(this);
     });
    });

var delFcuk = function(obj){
    var stallTimeId = $(obj).parent().attr("stallTimeId");
     var stallId 以上是关于如何优雅的用js动态添加html代码的主要内容,如果未能解决你的问题,请参考以下文章

JQuery - 动态添加Html后,如何使CSS生效,JS代码可用?

如何给html页面添加动态等待效果

js如何动态添加onclick。

JS动态添加下拉框跟文本域

JS动态添加div

用原生js怎么动态添加一个js文件