3 回答
TA贡献1828条经验 获得超3个赞
文档.querySelector()
Document 方法返回文档中与指定选择器或选择器组匹配的
querySelector()
第一个元素
您可以使用 定位所有元素,然后使用附加事件处理程序querySelectorAll()
循环遍历它们。forEach()
// JAVASCRIPT/JQUERY (to increment by 1)
let addRoom = document.querySelectorAll(".addRoom");
let subtractRoom = document.querySelectorAll(".subtractRoom");
addRoom.forEach((el)=>{
el.addEventListener('click', (e) => {
let input = e.target.closest('.bedroomsButton,.bathroomsButton').querySelector(".roomsAmmount");
input.value = parseInt(input.value) + 1;
});
});
subtractRoom.forEach((el)=>{
el.addEventListener('click', (e) => {
let input = e.target.closest('.bedroomsButton,.bathroomsButton').querySelector(".roomsAmmount");
input.value = parseInt(input.value) - 1;
});
});
<div class="bedroomsButton">Bedrooms
<div class="addRoom">
<span class="plusOne">+</span>
</div>
<div class="subtractRoom">
<span class="subtractOne">-</span>
</div>
<input class="roomsAmmount" type="number" value="0">
</div>
<div class="bathroomsButton">Bathrooms
<div class="addRoom">
<span class="plusOne">+</span>
</div>
<div class="subtractRoom">
<span class="subtractOne">-</span>
</div>
<input class="roomsAmmount" type="number" value="0">
</div>
TA贡献1801条经验 获得超8个赞
就像评论所说,document.querySelector只返回第一个元素或 null。
这样做:
let addRoom = document.querySelectorAll(".addRoom");
let subtractRoom = document.querySelectorAll(".subtractRoom");
addRoom.forEach(btn => {
setInputValue(btn, true)
}
)
subtractRoom.forEach(btn => {
setInputValue(btn, false)
}
)
function setInputValue(btn, plus) {
const input = btn.parentNode.querySelector('input')
btn.addEventListener('click', () => {
const originalValue = parseInt(input.value)
input.value = String(plus ? originalValue + 1 : originalValue - 1)
});
}
TA贡献1887条经验 获得超5个赞
clickable为每个 + 和 -添加类
选择全部clickable并在每个元素上添加事件侦听器
document.querySelectorAll(`.clickable`).forEach(el => el.addEventListener(`click`, handleClick))
handleClick函数看起来像这样
const handleClick = (e) => {
// selecting a closest input
const input = e.target.parentElement.parentElement.querySelector(".roomsAmmount");
// parsing value
let newValue = parseInt(input.value);
// if clicked element has class plusOne
if (e.target.classList.contains(`plusOne`)) {
newValue++; // increase
}
// if clicked element has class subtractOne
if (e.target.classList.contains(`subtractOne`)) {
newValue--; // decrease
}
// update value
input.value = newValue;
}
工作示例https://jsfiddle.net/yqp5zx1b/1/
- 3 回答
- 0 关注
- 79 浏览
添加回答
举报