我不知道如何使用事件目标 closest([name="..."])
据我了解closest()
应该在我更改输入字段中的值后获取元素进行计算,但我得到的元素是null
function calculate(e) {
if (e.target.name == 'qty') {
var elemPrice = e.target.closest('[name="price"]') //***
var elemAmount = e.target.closest('[name="amount"]') //***
console.log(elemPrice)
console.log(elemAmount)
elemAmount.value = elemPrice.value * e.target.value
}
}
document.addEventListener('DOMContentLoaded',function(){
document.getElementsByName('qty').forEach(t => { t.addEventListener('change',calculate) })
})
<table>
<tbody>
<tr class="uk-hidden">
<td>1</td>
<td><input name="price"></td>
<td><input name="qty"></td>
<td><input name="amount"></td>
</tr>
<tr class="uk-hidden">
<td>2</td>
<td><input name="price"></td>
<td><input name="qty"></td>
<td><input name="amount"></td>
</tr>
<tr class="uk-hidden">
<td>3</td>
<td><input name="price"></td>
<td><input name="qty"></td>
<td><input name="amount"></td>
</tr>
</tbody>
</table>
我试过了
...
var elemPrice = e.target.parentElement.previousElementSibling.lastElementChild //***
var elemAmount = e.target.parentElement.nextElementSibling.lastElementChild //***
...
但我想做 closest
有没有办法做到这一点 ?无论如何提前谢谢你
最佳答案
阅读文档总是一个好主意。如果我们看 https://developer.mozilla.org/en-US/docs/Web/API/Element/closest它说:
The closest() method traverses the
Element
and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returnsnull
.
所以它不会做你假设的事情:它只检查从你的元素到文档根的路径。你想要的是找到最近的
<tr>
,然后找到name=price
该元素内的元素:e.target.closest(`tr`).querySelector(`[name=price]`)
关于javascript - 如何从事件目标最接近(名称)中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63046477/