使用模板字符串Template Literal优化代码编写

语法

`abc ${expression}` 使用反引号连接 多行字符串和字符串插值

(1) 多行 ?代替换行符 \n
`line 1
 line 2`

 

(2) 表达式 
var x = 1; var y = town

const y = `There will be ${x*5} people in the ${y.toUpperCase()} next week.`

Result : There will be 5 people in the TOWN next week.

 

(3)HTML标签
`<ul>
    <li>${d}</li>
    <li>${d*2}</li>
    <li>Cancel ${d}</li>
</ul>`

 

var mode = $(this).val();
const row = `<tr data-mode=${mode}>
<td>${mode.toUpperCase()}</td>
<td>${mode} a obj</td>
<td>Cancel ${mode}</td>
</tr>`;

 

(4)转义

反引号内部插入, 要用 \` 或者 "`" 来转移反引号.

 

(5)函数标签
// as tagged template literal

const Button = styled.button`
  background: ${ props => props.background };
  color: ${ props => props.color };
`

// as Empty Array Pattern

const Button = styled.button([], props => ({
  background: props.background,
  color: props.color
}))

styled.button 是一个标签函数, 作用于后面两个变量. 


应用实例

场景

?checkbox, 在勾选的点击事件发生后,自动加入表格栏新数据, 在勾选移除后,数据也相应移除

具体代码

①HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  
<body>
 
<table id="permissionsTable">
  <thead>
    <th>Name</th>
    <th>Slug</th>
    <th>Description</th>
  </thead>
  <tbody id="tableBody">
    
  </tbody>
</table>

  <ul>
    <li>
      <input type="checkbox" value="Play" class="chx" />Play</li>
    <li>
      <input type="checkbox" value="Create" class="chx"/>Create</li>
    <li>
      <input type="checkbox" value="Delete" class="chx" />Delete</li>
  </ul>

</body>
</html>

②JS

$(".chx").change(function() {
   var row = document.createElement("tr");
   
    if(this.checked) { 
      var v = $(this).val();                   
      row.innerHTML = `<td>${v} Game</td>
                       <td>${v.toLowerCase()}-Game</td>
                       <td>Allow user to ${v.toUpperCase()} a Game</td>`;      
    row.setAttribute("name",$(this).val()); 
      $('#tableBody').append(row);  
    }
  else{    
    $("tr[name="+$(this).val()+"]").remove();
  }
});

 

实际效果

ps: 不知道为什么用chrome, 跳不出来, 用Firefox可以成功.

NameSlugDescription
  • Play
  • Create
  • Delete

转载于:https://www.cnblogs.com/yukwah/articles/10834458.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值