0

I have group of radio buttons like this: <form> <input class="answer" name="answer" value="10" type="radio">ans0<br> <input class="answer" name="answer" value="11" type="radio">ans1<br> </form> And I have place on page where I write how many times did you click on any radio button.

<p>Clicked:</p> <p id="clicked">0</p>

I need jquery to count all those clicks. Can you help me?

4

4 回答 4

1

将单击事件侦听器附加到您的单选按钮。然后在回调中读取元素中单击 id 的当前数字,将其解析为数字,加 1,然后将新值写入元素。

像这样的东西:

// Attach a click-event listener to your radio-buttons​
$("input[type='radio']")​.on("click", function () {
    // Cache the element
    var elm = $("#clicked");
    // Read the current value
    var count = parseInt(elm.text(), 10);
    // Update the element with the new value
    elm.text(count + 1);    
});​​​​​​​​

演示

于 2012-12-15T21:14:36.913 回答
0

您可以使用该click功能来捕获点击。

var counter = 0
$('input[name=answer]').click(function() {
  counter++
  $('#clicked').text(counter); // update text
});
于 2012-12-15T21:14:10.207 回答
0

尝试..

$(function(){
    var clicked = 0,
        radios = $('form input[type="radio"]'),
        clickBlock = $('#clicked');

    radios.click(function(){
        clicked++;
        clickBlock.html(clicked);
    });
});​
于 2012-12-15T21:17:45.350 回答
0

这是关于 jsFiddle 的一个工作示例,我在单选框 html 中放置了一个额外的属性来存储点击次数。如果这对您来说是一个选项,我认为它可以生成有效的干净代码,那么只需编写一个代码块来处理单击事件并显示每个单选按钮的单击 - 无论您有多少单选按钮

<input class="answer" name="answer" value="10" type="radio" data-clicked="0">ans0<br>
<input class="answer" name="answer" value="11" type="radio" data-clicked="0">ans1<br>​

$(function(){
    $('.answer').click(function(){
       var numOfClicks = $(this).attr('data-clicked');
       numOfClicks = (numOfClicks * 1) + 1;
       $(this).attr('data-clicked', numOfClicks);
       alert(numOfClicks);
    });    
});​
于 2012-12-15T21:18:46.457 回答