Jquery绑定事件不响应

时间:2012-08-09 20:56:26

标签: javascript jquery ruby-on-rails ruby unobtrusive-javascript

当按下一个按钮时,我试图基本上增加和减少一次投票计数(我已经愚弄了这个情况以利用我的错误);我用点击事件绑定两个不同的按钮;但是,我没有得到任何响应(用Firebug测试)。

Jquery代码:

//This Code is located within Application.js (Rails)
$(document).ready(function() {
    $('.buttonUp').bind('click', function() {
        var voting_element = $(this).closest('.current_vote');
        voting_element.text( Number(voting_element.text()) + 1 );
    });
    $('.buttonDown').bind('click', function() {
        var voting_element = $(this).closest('.current_vote');
        voting_element.text( Number(voting_element.text()) - 1 );
    });
});

每个带有buttonUp或buttonDown类的按钮都位于包含单个提交按钮的表单中。

我在Rails 3.1.3中使用以下版本的Jquery库:

Jquery-Rails => 1.0.12
Jquery => 1.6.1
JqueryUI => 1.8.12
JqueryUJS =>上面带有Jquery-Rails的那个。

Live也不起作用,因为在将方法绑定到按钮之前等待文档加载,我没想到会这样做。

以下是相关HTML的摘要。

<tr>
    <td>pop</td>
    <td>pop</td>
    <td><a href="/posts/12">Show</a></td>
    <td><a href="/posts/12/edit">Edit</a></td>
    <td><a href="/posts/12" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a></td>
    <td><p>
      <b>votes: </b>
    </p>
      <p class="current_vote">
        1
      </p>
      <form action="/posts/increaseVote?id=12" class="button_to" data-remote="true" data-type="json" method="post"><div><input class="buttonUp" type="submit" value="increaseVote" /><input name="authenticity_token" type="hidden" value="TxEGwONzSD+tnJ19iHMdGjuCBJMFoNJdECEspDtZxxY=" /></div></form>
      <form action="/posts/decreaseVote?id=12" class="button_to" data-remote="true" data-type="json" method="post"><div><input class="buttonDown" type="submit" value="decreaseVote" /><input name="authenticity_token" type="hidden" value="TxEGwONzSD+tnJ19iHMdGjuCBJMFoNJdECEspDtZxxY=" /></div></form>
  </tr>

1 个答案:

答案 0 :(得分:2)

要指出正确的方向,请查看此DEMO

这是JS:

$(document).ready(function() {

    function vote(el, amt) {
        var $counter = $(el).siblings('.counter');
        $counter.text(parseInt($counter.text(), 10) + amt);
    }

    $('.voteUp').bind('click', function() {
        vote(this, 1);
    });

    $('.voteDown').bind('click', function() {
        vote(this, -1);
    });

});​