【问题标题】:Question regarding RJS and usage of link_to_remote关于 RJS 和 link_to_remote 使用的问题
【发布时间】:2009-11-05 03:08:46
【问题描述】:

当我遇到这个问题时,我正在我的网站上工作,我的博客中有 100 个帖子,我一次将它们分页 10 个,我显示第 15 个并在底部显示一个链接,该链接基本上是使用实现的link_to_remote 标签。

<%= link_to_remote "More Posts", :url => {:action => 'view' ,:id => link.to_i + 1} , :html => {:id => 'more-link'} %>

我点击它并获取接下来的 15 个帖子,然后通过 insert_html 将其附加到包含第 15 个帖子的容器中

page.insert_html :bottom, :puzzles , :partial => 'puzzles', :object => @puzzles

现在我想要更新页面底部的链接,以便下次用户点击更多时获取第三批等等。基本上是这样的

page.replace_html 'more-link', link_to_remote "More Posts", :url => {:action => 'view' ,:id => link.to_i + 1} , :html => {:id => 'more-link'}

关于我如何做到这一点的任何线索?

【问题讨论】:

    标签: ruby-on-rails templates rjs


    【解决方案1】:

    你很亲密。

    replace_html 使用 (DOM_id, options for render) 调用。本质上,您想要呈现 link_to_remote 调用的输出。但是您并没有以 render 可以使用的形式传递它。正如 Barry Hess 指出的那样,替换更适合这项任务,因为您要更改的大部分内容是标签属性。

    使用 replace_html 会导致嵌套标签,这可能会导致问题。您想完全替换该元素。 Replace 具有与 replace_html 相同的语法,因此如果您只是将 replace_html 切换为替换,则会遇到相同的问题。

    这就是你想要的:

    page.replace 'more-link', :text => link_to_remote "More Posts", 
      :url => {:action => 'view' ,:id => link.to_i + 1} ,
      :html => {:id => 'more-link'}
    

    但是我不确定是否可以从 RJS 访问 link_to_remote。如果上述方法不起作用,您可以随时这样做:

    page.replace 'more-link', :inline => "<%= link_to_remote 'More Posts', 
      :url => {:action => 'view' ,:id => link.to_i + 1},
      :html => {:id => 'more-link'} %>", :locals => {:link => link}
    

    【讨论】:

    • 实际上,page.replace 会更好地替换整个元素,而不仅仅是内部 HTML。此外,为这个特定的link_to_remote 创建一个辅助方法可能会很好,这样所有的 URL 和 HTML 参数都不会重复。
    • @Barry,您对 replace 与 replace_html 的看法是完全正确的。事实上,replace_html 对这项工作来说是完全错误的。我已经根据您的建议更新了答案,并解释了导致 replace_html 错误的原因。
    • 你给我的解决方案完美运行,现在如果我想在 rjs 文件中有条件,基本上如果链接 == -1 的值我想用禁用的 html 属性替换链接,我该怎么做?
    • 链接不能被禁用,但可以隐藏。 RJS 只是 ruby​​,因此您可以将其全部包装在 if/else 块中,如果条件为真则替换元素,否则将其删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    相关资源
    最近更新 更多