语法
`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可以成功.
Name | Slug | Description |
---|
- Play
- Create
- Delete