jquery - Rails 和 JQuery - 无法禁用链接默认操作

标签 jquery ruby-on-rails

我有一个“已检查”链接,该链接会转到同名 Controller 操作。它作为 POST 请求进行路由。我已经设置了代码,但发生的情况是 jquery $.post 按需要触发,但 html 请求也发生了,这意味着我的操作被调用了两次。我不明白为什么。有人能发现我犯的错误吗?

在我的 application.js 中

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

$(document).ready(function() {
 $('ul li.sentence_summary a.correct').click(function(){
      $(this).css("border", "1px black solid");
      $.post($(this).attr("href"), null, null, "script");
      return false;
    });

});

在我的 Controller 中

 def check
    @sentence_author = User.find(params[:user_id])
    @sentence = @sentence_author.sentences.find(params[:id])
    @sentence.checked_at = Time.now
    @sentence.checker_id = current_user.id
    respond_to do |format|
      if @sentence.save!
        flash[:notice] = "Thank you for checking #{@sentence_author.to_s}s sentence."
        format.js {  }
        format.html { redirect_to user_foreign_sentences_path(current_user, :display => :pending) }
        format.xml  { head :ok }
      end
    end
  end

在 actions js 文件中

alert("testing123");

更新

我的 View 呈现了带有此部分的句子集合。部分依次调用如下所示的 View 辅助方法来呈现链接

%li{:id => ["sentence", "#{sentence.id}"], :class => "sentence_summary bottom_border_light"}
  %div.left
    = thumbnail_link_to_user_profile(sentence.user, User::GRAVATAR_M)
  %div.left.main_info_container
    %div
      = link_to_user_profile(sentence.user)
      = t('sentences.table.wrote')
    %div.main_focus

      = sentence.text
    %div.bottom_bar
      %div.left
        = created_at_linked_to_sentence_show_path(sentence)
      %div.right.rollover_options
        = render_check_options(sentence)
        = render_edit_options(sentence)
        = render_flag(sentence)
      %div.clear
  %div.clear

这个助手会呈现有问题的链接

  def render_check_options( sentence)
    if sentence.user != current_user and sentence.language == current_user.native_language and sentence.pending?
      html = link_to("correct", check_user_sentence_path(sentence.user, sentence), :method => "post", :class => "action_options underline_on_hover always_blue correct")
      html += link_to("incorrect", new_sentence_correction_path(sentence), :class => "action_options underline_on_hover always_blue incorrect")
      return html
    end
  end

更新2* 根据托尼的建议,这是我的 Firebug 控制台中发生的情况

console.debug($('ul li.sentence_summary a.correct'));

按预期输出正确的链接(我点击这些链接,它们会转到正确的 html)

[a.action_options /users/9...24/check, a.action_options  /users/2...26/check, a.action_options /users/2...27/check, a.action_options  /users/9...28/check, a.action_options /users/1.../8/check, a.action_options  /users/2...10/check, a.action_options /users/1...11/check, a.action_options  /users/9...12/check]

但即使运行以下两个命令后,链接也不会被禁用

   $('ul li.sentence_summary a.correct').unbind('click');


    $('ul li.sentence_summary a.correct').click(function(){
          return false;
        });  

对于 ul 中的第一个 li,我的 html 看起来像这样(请注意,除非翻转,否则相关链接是隐藏的,因此此处的显示设置为:隐藏。)

        <div class="left">
          <a href="/users/9"><img alt="D03e17968fe80cd2d3816e86a7e072f9" class="avatar" src="http://gravatar.com/avatar/d03e17968fe80cd2d3816e86a7e072f9.png?d=identicon&amp;r=PG&amp;s=45"></a>
        </div>
        <div class="left main_info_container">
          <div>
            <a href="/users/9" class="user_name_link underline_on_hover always_blue">maxwell.wiegand</a>
            wrote
          </div>
          <div class="main_focus">
            Aspernatur eum tenetur dolorem impedit dolor modi illum.
          </div>
          <div class="bottom_bar">
            <div class="left">
              <a href="/users/9/sentences/24" class="meta-data underline_on_hover">2 days ago</a>
            </div>
            <div style="display: none;" class="right rollover_options">
              <a href="/users/9/sentences/24/check" class="action_options underline_on_hover always_blue correct" onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'post'); f.appendChild(m);var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'ZD3boP6x3HjxzvLBQmTsJT2xCWGQoq8j7M0ZSD6UGbE='); f.appendChild(s);f.submit();return false;">correct</a><a href="/sentences/24/corrections/new" class="action_options underline_on_hover always_blue incorrect">incorrect</a>

              <a href="/sentences/24/flags/new" class="action_options underline_on_hover always_blue">flag</a>
            </div>
            <div class="clear"></div>
          </div>
        </div>
        <div class="clear"></div>

最佳答案

尝试删除

$(this).css("border", "1px black solid");
      $.post($(this).attr("href"), null, null, "script");

只需返回 false 并告诉我发生了什么

更新

如果您将链接的 onclick 设置为返回 false,则该链接将无处可去。我会检查两件事 -

1) 确保选择器正确: 当你这样做时,输出是什么?

console.debug($('ul li.sentence_summary a.correct'));

2) 确保没有其他点击处理程序干扰: 检查完 #1 后,打开 JS 控制台并执行以下操作:

$('ul li.sentence_summary a.correct').unbind('click');

这将解除所有点击事件的绑定(bind),包括您想要发生的事件。然后通过在控制台中执行常用代码来重新绑定(bind)单击事件(仅在单击处理程序中返回 false)。这将确保只有一个处理程序监听链接的单击事件,并且该处理程序将返回 false 并且不执行该链接。

3) 发布生成的相关 HTML,以便我们查看

关于jquery - Rails 和 JQuery - 无法禁用链接默认操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3141405/

相关文章:

javascript - 动画命令完成后调用命令

javascript - 在 keyup 事件中找不到结果时显示

ruby-on-rails - Ruby on Rails 3 - 使用 View 和 Controller 创建插件或引擎?

ruby-on-rails - "bundle update"会更新系统上的所有 gem 还是只更新 Gemfile 中的 gem?

ruby-on-rails - 更改 :id parameter in Routing resources for Rails 的名称

javascript - JavaScript中异步Ajax调用的测试结果

css - 基于类用jQuery添加css

javascript - 当我在自身内部调用函数时,来自 Math.random 的值会导致问题

ruby-on-rails - Rails 没有使用正确版本的 Ruby

ruby-on-rails - Rails:您已经激活了 rake 10.3.1,但您的 Gemfile 需要 rake 10.2.2 (Gem::LoadError)