如何从事件路径的特定 HTML 节点 return 属性
How to return properties from specific HTML node from event path
我有一个带有图像和文本的按钮,如下所示:
<button on-tap="doSomething">
<img src="./path/to/img.png">
<p>Text<p>
</button>
我想将按钮文本传递到过滤器中
function doSomething(e) {
console.log(e.path[0].innerText);
}
但是,路径会根据单击按钮的位置而变化。如果单击图像而不是按钮空白,则正确的文本位于 e.path[0].innerText
.
我想我可以在找到第一个按钮后遍历路径和 return,但我不确定如何匹配 select 或名称。
function doSomething(e) {
e.path.forEach(el => {
if (el.name === 'button') console.log(el.innerText);
}
}
或者我可以将数据绑定到图像和按钮,但这似乎是错误的方法。
如何从路径中 select 按钮并检索其 innerText
?
您可以尝试将 tagName
属性 与 target
元素一起使用:
function doSomething(e) {
if (e.target.tagName === 'BUTTON') {
console.log(e.target.innerText);
}
}
<button onclick="doSomething(event)">
<img src="./path/to/img.png">
<p>Text<p>
</button>
或:
var button = document.querySelector('button');
button.addEventListener('click', function (e) {
if (e.target.tagName === 'BUTTON') {
console.log(this.innerText);
}
});
<button>
<img src="./path/to/img.png">
<p>Text<p>
</button>
我有一个带有图像和文本的按钮,如下所示:
<button on-tap="doSomething">
<img src="./path/to/img.png">
<p>Text<p>
</button>
我想将按钮文本传递到过滤器中
function doSomething(e) {
console.log(e.path[0].innerText);
}
但是,路径会根据单击按钮的位置而变化。如果单击图像而不是按钮空白,则正确的文本位于 e.path[0].innerText
.
我想我可以在找到第一个按钮后遍历路径和 return,但我不确定如何匹配 select 或名称。
function doSomething(e) {
e.path.forEach(el => {
if (el.name === 'button') console.log(el.innerText);
}
}
或者我可以将数据绑定到图像和按钮,但这似乎是错误的方法。
如何从路径中 select 按钮并检索其 innerText
?
您可以尝试将 tagName
属性 与 target
元素一起使用:
function doSomething(e) {
if (e.target.tagName === 'BUTTON') {
console.log(e.target.innerText);
}
}
<button onclick="doSomething(event)">
<img src="./path/to/img.png">
<p>Text<p>
</button>
或:
var button = document.querySelector('button');
button.addEventListener('click', function (e) {
if (e.target.tagName === 'BUTTON') {
console.log(this.innerText);
}
});
<button>
<img src="./path/to/img.png">
<p>Text<p>
</button>