第一次发博客。发一个今天学习的百度面试题吧(有点激动)
**题目:**用js实现一个用户行收集器,功能如下:
1,收集用户在页面中的所有click行为,并使用log方法发送日志,包含触发事件的节点xpath信息
2,xpath需包含tagName、id、class、同级同名节点索引(从1开始),如
something
点击target link时,xpath为 body[1]/div[1][@id=“container”]/a[2][@id=“link2”][contains(@class, “link-class")][contains(@class, “current")]
3,不侵入、不影响其他业务代码的执行
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2019_31</title>
<style>
body {
height: 500px;
background-color: pink;
}
</style>
</head>
<body>
<div id="container">
<p>something</p>
<a id="link1" class="link-class">mmm</a>
</div>
<div id="container2">
<a id="link2" class="link-class current">target link</a>
</div>
<script>
let body = document.body;
let bodys = document.getElementsByTagName("body")[0];
console.log(bodys);
console.log(body);
document.body.addEventListener('click', (event) => {
// console.log(event);
console.log(getPath(event.target));
})
//获取path
function getPath(target) {
if (target.nodeName == 'BODY') {
return 'body[1]'
// console.log('ccc');
} else {
var index = 1;
var xpath = '';
// console.log(target);
let nodetarget = target;
let tagName = target.nodeName;
let tagClass = target.classList;
let tagId = target.id;
var str = '';
// console.log(tagName, tagClass, tagId);
// console.log(target.previousElementSibling);
while (nodetarget.previousElementSibling != null) {
if (nodetarget.previousElementSibling.nodeName == tagName) {
index++;
// console.log(index);
}
nodetarget = nodetarget.previousElementSibling;
}
str = `\/${tagName.toLowerCase()}[${index}][@id = "${tagId}"]`
tagClass.forEach((element, i) => {
str = `${str}[contains(@class,"${element}")]`
});
}
return getPath(target.parentNode) + str;
}
</script>
</body>
</html>