我們需要有一個(gè)對(duì)象,將DOM節(jié)點(diǎn)和對(duì)應(yīng)的數(shù)據(jù)一一映射起來。
以此來達(dá)到修改DOM相關(guān)的任意一個(gè)屬性的時(shí)候,只修改它所對(duì)應(yīng)的節(jié)點(diǎn)。而不是去渲染更新整個(gè)DOM。
<p>姓名:{{name}},年齡:{{age}}</p>
p標(biāo)簽中的姓名:{{name}},年齡:{{age}}是一個(gè)文本節(jié)點(diǎn)。在進(jìn)行節(jié)點(diǎn)對(duì)象構(gòu)建時(shí),需將這個(gè)文本節(jié)點(diǎn)拆分成多個(gè),以此來達(dá)到精確匹配。舉個(gè)栗子,上面的這個(gè)文本節(jié)點(diǎn)需要拆分成 [“姓名:”,“name”,"年齡",“age”].
我們通過正則來實(shí)現(xiàn)這一需求。
- 首先列舉出JavaScript RegExp 對(duì)象中的幾個(gè)方法:
test() //檢索字符串中的指定值。返回值是 true 或 false。
exec() // 檢索字符串中的指定值。返回值是被找到的值。如果沒有發(fā)現(xiàn)匹配,則返回 null。
compile() //可以改變檢索模式,也可以添加或刪除第二個(gè)參數(shù)。
- 具體代碼如下。主要思路是通過RegExp對(duì)象的exec方法進(jìn)行全文檢索。
<script type="text/javascript">
// 姓名:{{user.name}},年齡:{{user.age}}
var pendingText = "姓名:{{user.name}},年齡:{{user.age}}"
function parseText(pendingText){
var collection=[];
var searchTxt="";
var targetTxt = "";
var stringLength=0,lastIndex=0,curIndex=0;
var reg =/\{\{(.+?)\}\}/g;
if(!reg.test(pendingText)){
throw new Error("未匹配");
}else{
reg.lastIndex=0;
while( tempR = reg.exec(pendingText))
{
curIndex = reg.lastIndex;
searchTxt=tempR[0];
stringLength=searchTxt.length;
collection.push(pendingText.slice(lastIndex,curIndex-stringLength));
targetTxt=tempR[1];
collection.push(targetTxt);
lastIndex=curIndex;
}
}
console.log(collection);
}
parseText(pendingText);
</script>