判断该元素的子元素里是否有某一个属性(如 data-Id),如果有,则获取,如果没有,则向上冒泡,一直到子元素有该属性位置,在父元素上设置一个ref属性,判断如果第一次点击的是父元素,则不再冒泡,直接返回
<template>
<div ref="parent" @click="handleClick">
<div class="child">
<h2>Child 1</h2>
<p class="desc">Lorem ipsum <b data-id="1">dolor</b> sit amet, consectetur adipiscing elit.</p>
<p class="content">Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="child">
<h2>Child 2</h2>
<p class="desc">Ut enim ad <span data-id="2">minim veniam</span>, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p class="content">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
</div>
</template>
<script>
export default {
methods: {
handleClick(event) {
const target = event.target;
if (!target.hasAttribute('data-id')) {
return; // 如果点击元素没有该属性,直接返回
}
const elements = [];
let el = event.target;
while (el) {
if (el.hasAttribute('data-id')) {
// 如果找到一个拥有目标属性的元素,则将其加入数组
elements.push({
id: el.getAttribute('data-id'),
tagName: el.tagName.toLowerCase(),
className: el.className || undefined,
});
}
el = el.parentNode; // 向上冒泡,继续查找上一级父元素是否有目标属性
}
console.log(`Clicked element (data-id: ${target.getAttribute('data-id')}) has ancestors with matching properties:`, elements);
},
},
};
</script>