我试图做一个按钮,点击他的ID和变量递增.我能够在StackOverflow上找到一些增加输入字段值的代码,但我不知道从那里改变它.
这是标记:
<input type="text" name="qty" value="0" />
<p id="inc">Increase</p>
<p id="dec">Decrease</p>
Run Code Online (Sandbox Code Playgroud)
和jQuery
<script>
$(document).ready(function()
{
$(function()
{
$("#inc").click(function()
{
$(":text[name='qty']").val(Number($(":text[name='qty']").val()) + 1);
$('#inc').addClass (Number + 1); // this one does not work
var incrementVar = (Number + 1); // this one also does not work
});
$("#dec").click(function()
{
$(":text[name='qty']").val(Number($(":text[name='qty']").val()) - 1);
});
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
这确实增加了输入中的val,但我不能使它增加$('#inc')类和var incrementVar.
我该怎么办?谢谢
类名不能以数字开头,详见此讨论.如果你在你的班前写说.c1,.c2等等......你可以这样做:
$(function() {
$("#inc").click(function() {
var num = $(":text[name='qty']").val(function(i, v) {
return Number(v) + 1;
}).val();
$(this).addClass ('c' + num);
var incrementVar = num;
});
$("#dec").click(function() {
$(":text[name='qty']").val(function(i, v) { return Number(v) - 1; });
});
});
Run Code Online (Sandbox Code Playgroud)
还有一点需要注意:没有必要,$(document).ready(function() {而且$(function() {这些都是等价的,只用一个包装就可以了.
var incrementVar = 0;
$(function() {
$("#inc").click(function() {
var value = parseInt($(":text[name='qty']").val()) + 1;
$(":text[name='qty']").val(value);
$('#inc').addClass('a' + value); // I believe class names cannot start with a number
incrementVar = incrementVar + value;
});
});
Run Code Online (Sandbox Code Playgroud)