jquery - Rails,单击时更改 HTML 元素的类属性

标签 jquery html css ruby-on-rails ruby

我正在实现邮箱系统的 View 。我想要InboxSent 邮箱。因此,我在 View 中放置了两个链接,例如:

<%= link_to "Inbox", messages_user_path(current_user),:class =>"current", :which_mailbox => "received" %>
<%= link_to "Sentbox", messages_user_path(current_user),:class =>"current", :which_mailbox => "sent" %>

然后我希望我的 Controller 根据 `params[:which_mailbox] 获取适当的消息。如:

def fetch_messages
    if params[:which_mailbox] == "received"
      @messages= current_user.received_messages
    else if params[:which_mailbox] == "sent"
      @messages = current_user.sent_messages
    end

    render 'users/messages_page'
end

与其他选项相比,我想使用粗体字体设置所选邮箱(即 `class="current")的样式。

a .current{
    font-weight: bold;    
}

问题 是这两个选项(收件箱/已发件箱)都有 class="current" 使用上面的 link_to .. 代码。如何激活/停用此类?可以不用 Javascript 吗?那只是使用 Rails+ CSS?

编辑 这是生成的 HTML:

    <section>
  <a href="/users/1/messages" class="current" which_mailbox="received">Inbox</a>
</section>
<section>
  <a href="/users/1/messages" class="current" which_mailbox="sent">Sent</a>
</section>

我现在意识到没有params[:which_mailbox],我想我应该初始化 key which_mailbox,推荐的地方在哪里?

最佳答案

由于您进行了整页重新加载,因此无需在此处涉及 javascript。您可以只呈现适当的类。

<%= link_to "Inbox", messages_user_path(current_user, :which_mailbox => "received"),
                    :class => params[:which_mailbox] == 'received' ? 'current' : '' %>

您可以通过将逻辑移至帮助程序来稍微简化此代码

module MailboxesHelper
  def mailbox_link_class(this_mailbox, current)
    this_mailbox == current ? 'current' : ''
  end

  def mailbox_link(label, type)
    link_to label, messages_user_path(current_user, :which_mailbox => type),
                      :class =>mailbox_link_class(type, params[:which_mailbox])
  end
end

<%= mailbox_link 'Inbox', 'received' %>
<%= mailbox_link 'Sentbox', 'sent' %>

关于jquery - Rails,单击时更改 HTML 元素的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19465120/

相关文章:

javascript - 弹出编码避免浏览器阻塞

jquery - .removeClass() 不适用于过滤搜索和分页单击

html - 如何在我的 html 中使用来自 Flaticon 的图标?

jquery - 用于网格布局的高效 DIV 结构

html - 我的行占据了太多的高度

css - 使用 CSS 将(背景)图像放在网站内容旁边

html - 隐藏的CSS水平导航子菜单

jquery - Chrome自动填写而不提交表单

jquery - 每个 Div 加载时淡入多个 Div

jquery - 位置绝对 TD 在可见后留下空白空间