我试图使每个按钮增加其自己div中输入的数字,但不起作用。
var c = 0;
$(".up").click(function() {
var vote = document.getElementById('vote');
$(vote).find(".counter").val(c);
c++;
});
$(".down").click(function() {
var vote = document.getElementById('vote');
$(vote).find(".counter").val(c);
c = c - 1;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="votewrap">
<div id="vote">
<button class="up">up</button>
<input class="counter">
<button class="down">down</button>
</div>
<div id="vote">
<button class="up">up</button>
<input class="counter">
<button class="down">down</button>
</div>
</div>
答案 0 :(得分:0)
id
每页应该唯一,因此您只能有一个。 getElementById
方法将返回找到的投票的第一个值,因为它只是期望值。
答案 1 :(得分:0)
要对多个元素进行分组,请使用
class
属性。
您的代码似乎有多个错误,我已经使用.siblings()
和.closest()
方法解决了它们!
$(".up").click(function() {
var vote = $(this).closest('.vote'); // find the closest div
var c = $(this).siblings('.counter').val(); // get current value
$(vote).find(".counter").val(++c); // increment and set again
});
$(".down").click(function() {
var vote = $(this).closest('.vote'); // find the closest div
var c = $(this).siblings('.counter').val(); // get current value
$(vote).find(".counter").val(--c); // decrement and set again
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="votewrap">
<div class="vote"> <!-- use class instead of id -->
<button class="up" id='1'>up</button>
<input class="counter" value='0'> <!-- Set initial value to 0 -->
<button class="down">down</button>
</div>
<div class="vote"> <!-- use class instead of id -->
<button class="up" id='2'>up</button>
<input class="counter" value='0'> <!-- Set initial value to 0 -->
<button class="down">down</button>
</div>
</div>
答案 2 :(得分:0)
我已经对您的代码进行了一些修改,以分隔两个字段。我做了很长的路要走,以帮助理解。我给您的每个元素都提供了一个ID,以使它们彼此之间唯一。我还在您的点击处理程序中上调了您的计算结果,以免出现奇怪的加/减行为。
var c1 = 0;
$("#up1").click(function() {
var vote1 = document.getElementById('vote1');
c1++;
$(vote1).find("#counter1").val(c1);
});
$("#down1").click(function() {
var vote1 = document.getElementById('vote1');
c1 = c1 - 1;
$(vote1).find("#counter1").val(c1);
});
var c2 = 0;
$("#up2").click(function() {
var vote2 = document.getElementById('vote2');
c2++;
$(vote2).find("#counter2").val(c2);
});
$("#down2").click(function() {
var vote2 = document.getElementById('vote2');
c2 = c2 - 1;
$(vote2).find("#counter2").val(c2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="votewrap">
<div id="vote1">
<button id="up1">up</button>
<input id="counter1">
<button id="down1">down</button>
</div>
<div id="vote2">
<button id="up2">up</button>
<input id="counter2">
<button id="down2">down</button>
</div>
</div>