我有一个+和 - 按钮。我需要让它们根据点击增加或减少输入值。我尝试了以下代码:
的 HTML 的
<label for="CAT_Custom_410672">Veloce</label>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<ul class="button-group button-click">
<li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
<li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
</ul>
的 JS 的
$(function() {
$(".button-click").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
})
});
如何更正脚本才能正常运行?
注意:不会抛出任何错误。它只是不起作用。
答案 0 :(得分:1)
问题是您正在选择.button-click
,而这是父列表的类
试试这个:
$(function() {
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
if ($button.text() == "+") {
var newVal = parseInt(oldValue) +1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").prev().val(newVal);
})
});
答案 1 :(得分:1)
<label for="CAT_Custom_410672">Veloce</label>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<ul class="button-group button-click">
<li><a href="#" class="small button secondary my_button"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
<li><a href="#" class="small button secondary my_button"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
</ul>
$(document).ready(function() {
$(".my_button").on("click", function(event){
event.preventDefault();
var $button = $(this);
var oldValue = $('#CAT_Custom_410672');
var newVal;
if ($button.find('.hide').text() == "+") {
newVal = parseFloat(oldValue.val()) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue.val() > 0) {
newVal = parseFloat(oldValue.val()) - 1;
} else {
newVal = 0;
}
}
oldValue.val(newVal);
});
});