解释器模式:对于一种语言,给出其文法表示形式,并定义一种解释器,通过使用这种解释器来解释语言中定义的句子
使用场景:统计页面中点击事件粗发元素在页面所处的路径。
代码实现
<div id="container">
<div>
<div>
<ul>
<li><span id="span1"></span></li>
<li><span id="span2"></span></li>
</ul>
</div>
</div>
<div>
<div>
<ul>
<li><span id="span5"></span></li>
<li><span id="span6"></span></li>
</ul>
</div>
</div>
</div>
<script>
// xPath解释器
var Interpreter = (function () {
// 获取兄弟元素名称
function getSulingName(node) {
if (node.previousSibling) {
var name = '',
count = 1,
nodeName = node.nodeName,
sibling = node.previousSibling
while (sibling) {
if (sibling.nodeType == 1 && sibling.nodeType === node.nodeType && sibling.nodeName) {
// 如果节点名称和前一个兄弟元素名称相同
if (nodeName == sibling.nodeName) {
name += ++count
} else {
count = 1
name += '|' + sibling.nodeName.toUpperCase()
}
}
sibling = sibling.previousSibling
}
return name
} else {
return ''
}
}
return function (node, wrap) {
var path = [],
wrap = wrap || document
if (node == wrap) {
if (wrap.nodeType == 1) {
path.push(wrap.nodeName.toUpperCase())
}
return path
}
if (node.parentNode !== wrap) {
path = arguments.callee(node.parentNode, wrap)
}
else {
if (wrap.nodeType == 1) {
path.push(wrap.nodeName.toUpperCase())
}
}
var sublingsNames = getSulingName(node)
if (node.nodeType == 1) {
path.push(node.nodeName.toUpperCase() + sublingsNames)
}
return path
}
})()
var path = Interpreter(document.getElementById('span5'))
console.log(path)
</script>