我有一個購物車查看 購物車串列計數 和此檔案
<div class="input-group input-number-group">
<div class="input-group-button" onclick="decrement_cart(this)">
<span class="input-number-decrement">-</span>
</div>
<input class="input-number text-center" type="number"
value="{{ $detail['product_quantity'] }}" min="0" max="1000">
<div class="input-group-button" onclick="increment_cart(this)">
<span class="input-number-increment"> </span>
</div>
</div>
我想通過單擊增量/減量 div 來更改中間輸入值。注意:我不能使用 addEventListener 因為這個檔案是由 ajax 創建的。
如何通過單擊更改輸入值?
function increment_cart(elem) {
console.log(elem.closest('input'));
}
uj5u.com熱心網友回復:
沒有理由不能使用 addEventListener 添加事件處理程式。即使您嘗試附加處理程式的元素是在加載檔案后動態創建的。但是由于您沒有按時指定有關該時間點的任何詳細資訊,我所能做的就是建議如何從事件處理程式中選擇兄弟元素,稱為您在 html 代碼中指定的方式(使用行內事件處理程式)。這種方法不是很好,因為您只能以這種方式附加一個處理程式,并且它沒有嚴格系結到明確的范圍,而是系結到將被評估的字串。
無論如何,要在嘗試獲取兄弟姐妹時嚴格解決您的問題,您應該使用.next()and .prev()(JQuery) 來獲取下一個和上一個兄弟姐妹。
但是,由于您在尋找更好的解決方案,因此我向您展示了如何將這些函式附加為所有.input-number-increment和.input-number-decrement使用該attachHandlers函式的點擊事件的事件處理程式,以及這些處理程式應如何處理event.target以獲取對觸發事件的元素的參考以及如何使用.closest()首先檢索父級然后在其子級中.find()獲取所需元素。input
這是一個演示概念的演示(在您的代碼之上添加):
//I'm calling the attachHandlers on page load (but you have to call it once the elements are created)
attachHandlers();
function attachHandlers(){
$('.input-number-increment').on('click', increment_cart);
$('.input-number-decrement').on('click', decrement_cart);
}
function increment_cart(event) {
//gets the element triggerring the event
const target = event.currentTarget;
//gets the input element, finding it among the children of .input-number.group parent
const o = $(target).closest('.input-number-group').find('input');
const currValue = (o.val() === undefined || o.val() === '') ? 0 : parseInt(o.val());
o.val( currValue 1 );
}
function decrement_cart(event) {
//gets the element triggerring the event
const target = event.currentTarget;
//gets the input element, finding it among the children of .input-number.group parent
const o = $(target).closest('.input-number-group').find('input');
const currValue = (o.val() === undefined || o.val() === '') ? 0 : parseInt(o.val());
o.val( currValue-1 );
}
.input-group-button{
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group input-number-group">
<div class="input-group-button">
<span class="input-number-decrement">-</span>
</div>
<input class="input-number text-center" type="number" value="0" min="0" max="1000">
<div class="input-group-button">
<span class="input-number-increment"> </span>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480797.html
標籤:javascript jQuery 最近的 兄弟姐妹
下一篇:在表單提交上獲得空輸入
