写这篇文章,主要是想mark一下,因为JS动态生成HTML(这里都默认是生成大段的HTML,而不是简单的标签元素),常用的两种语法格式:
一种是es6的写法,反撇,' `` ',在英文语法输入状态下,esc正下方的按键。但是这种语法存在兼容性的问题,我在移动端的项目中遇到过,使用JQuery,没有使用框架。因为有一整个页面都是使用JS动态生成的HTML,所以,在一款华为手机自带的浏览器中不识别 `` ,页面空白。
另一种是字符串拼接,但是这种方式,拼接方法及方法入参时特别特别特别的繁琐,特别要注意单引号和双引号的使用,在外层双引号里单双引号,代码如下:
goodsHtml += '<div class="goods-list-line">' + '<div class="goods-show">' + '<img class="goods-img" alt="goodsImg" src=' +resGoodsInfo.logoUrl+ '>' + '<p class="goods-name small-text-style">' + resGoodsInfo.goodsName + '</p>' + '</div>' + '<div class="btn-line">' + '<div class="display-inline-block">' + "<button class='left-btn exchangeBtn display-inline-block button-style font-color-white' id=exchangeId"+i+" onclick=lookUpBtnClick('"+ resGoodsInfo.goodsId +"','" + resGoodsInfo.cardId +"') >查看</button>"+ '</div>' + '<div class="position-rel display-inline-block">' + "<button class='display-inline-block button-style font-color-white' id=consignId"+i+" onclick=consignBtnClick('"+ resGoodsInfo.goodsId +"','" + resGoodsInfo.cardId +"') >回收</button>"+ "<div class='recycle-price-text orange-color-text'>(得" + resGoodsInfo.recyclePrice + "元)</div>"+ '</div>' + '</div>' + '</div>'
下面附上es6的格式:
goodsHtml += `<div class="goods-list-line"> <div class="goods-show"> <img class="goods-img" src="${resGoodsInfo.logoUrl}" alt="goodsImg"> <p class="goods-name small-text-style">${resGoodsInfo.goodsName}</p> </div> <div class="btn-line"> <div class="display-inline-block"> <button id="exchangeId${i}" class=" left-btn exchangeBtn display-inline-block button-style font-color-white " onclick="lookUpBtnClick('${resGoodsInfo.goodsId}', '${resGoodsInfo.cardId}')" >查看</button> </div> <div class="position-rel display-inline-block" > <button id="consignId${i}" class=" display-inline-block button-style font-color-white" onclick="consignBtnClick('${resGoodsInfo.goodsId}', '${resGoodsInfo.cardId}')" >回收</button> <div class="recycle-price-text orange-color-text">(得${resGoodsInfo.recyclePrice}元)</div> </div> </div> </div>`
来源:oschina
链接:https://my.oschina.net/u/3694370/blog/1828936