Warm tip: This article is reproduced from serverfault.com, please click

html-jQuery从click类获得不同的价值

(html - jQuery to get different value from on click class)

发布于 2020-11-28 06:57:53

我想从课堂上获得价值,并定义了价值

<input type="checkbox" class="cat" value="3">
<input type="checkbox" class="cat" value="5">
<input type="checkbox" class="cat" value="8">

和我的jQuery代码

$('.cat').click(function(){
          var cat = Number($('.cat').val());
        $(".cat").val(cat);
 // after that using my code

}
Questioner
v2mpire 20202
Viewed
11
Sina Riani 2020-11-28 15:49:07

在选择器中删除$(".cat").val(cat);并使用this而不是'.cat'

$('.cat').click(function(){
            var cat = Number($(this).val());
            // after that using my code
    });

$(function(){
            $('.cat').click(function(){
                        var cat = Number($(this).val());
                console.log("cat value: " + cat);
                        // after that using my code
            });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="checkbox" class="cat" value="3">
<input type="checkbox" class="cat" value="5">
<input type="checkbox" class="cat" value="8">