我有一個按鈕。當我點擊它時,我想在控制臺中看到我的按鈕元素之前的當前輸入數字(這不是最終目標,但如果我能做到,其余的就不會有問題)。
我使用我的代碼所得到的只是undefined. 有人可以向我解釋什么是錯的以及如何做嗎?
$(".ajoutPanier").click(function() {
var nb = $(this).prev(".inputNbArt").val();
console.log(nb);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="nbArticles">
<input class="inputNbArt" type="number" max="10" min="1" value="1">
</form>
<a href="#openModal">
<button class="ajoutPanier">Ajouter Au panier</button>
</a>
uj5u.com熱心網友回復:
這里有兩個問題。首先,button元素內有一個a元素是無效的 HTML。我建議取而代之的是洗掉它button并將class其放在上面a。然后,您可以a根據需要使用 CSS 來設定元素的樣式。
其次,您使用的 DOM 遍歷方法不太正確。該.inputNbArt元素是 的子元素form,而不是被點擊的元素.ajoutPanier。要更正該問題,請使用prev()獲取同級form,然后使用find()。嘗試這個:
$(".ajoutPanier").click(function() {
var nb = $(this).prev('.nbArticles').find('.inputNbArt').val();
console.log(nb);
});
/* example button styling */
a.ajoutPanier {
background-color: #CCC;
display: inline-block;
padding: 5px 10px;
margin: 5px 0;
border-radius: 5px;
box-sizing: border-box;
text-decoration: none;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="nbArticles">
<input class="inputNbArt" type="number" max="10" min="1" value="1">
</form>
<a href="#openModal" class="ajoutPanier">Ajouter Au panier</a>
uj5u.com熱心網友回復:
因為您的 HTML 無效(請參閱注釋,我們無法確定 DOM 在任何給定瀏覽器中的外觀,因為它們可以做任何需要使結構有效的事情。
當您單擊按鈕時,this處理程式內部將是該button元素。prev只找到以前的兄弟姐妹,但你要找的元素不是兄弟姐妹,它是按鈕父元素的前兄弟的孩子(如果瀏覽器沒有重新定位button,它很可能會重新定位)。
你可以使用:
$(this).parent().prev().find(".inputNbArt")
但它相當脆弱。相反,考慮將整個結構放在父元素中,然后:
$(this).closest("selector-for-parent-element").find(".inputNbArt")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366596.html
標籤:javascript 查询
上一篇:字串內的條件不起作用-角度
