Jquery:检查选择器返回错误计数

时间:2014-05-12 01:52:49

标签: jquery html

我有点疑惑为什么会发生这种情况。

我使用了jQuery API库中的jQuery :checked选择器。这里有趣的是我计算一个类中的所有单选按钮(通过或失败),然后将它们添加到显示百分比/计数。单击多个无线电后,此功能正常,但在选中的第一个单选按钮上,它将返回2.

HTML:

<b>
    <input type="radio" name="storeprestidy" value="pass"  class="storepresg" />
    <input type="radio" name="storeprestidy" value="fail" class="storepresp"  /><br />
    <input type="radio" name="storepresclean" value="pass"  class="storepresg" />
    <input type="radio" name="storepresclean" value="fail" class="storepresp"  /><br />
    <input type="radio" name="storepreslights" value="pass"  class="storepresg" />
    <input type="radio" name="storepreslights" value="fail" class="storepresp"  />
</b>

的javascript:

var countChecked = function () {
    var sg = $("input.storepresg:checked").length;
    $("#storepresgtotal").text(sg + (sg === 1));
};
countChecked();
$("input[type=radio]").on("click", countChecked);

因此,如果我点击课程storepresg中的2个或更多单选按钮,则计数正确。它仅在第一个选择时返回错误的数字(2)。

第一次发表海报,希望我能正确提出问题。

感谢。

1 个答案:

答案 0 :(得分:0)

删除它:

+ (sg === 1)

来自:

$("#storepresgtotal").text(sg + (sg === 1));

应该是这样的:

$("#storepresgtotal").text(sg);

表现得像这样:http://jsfiddle.net/zdCLm/1/