"received" %-6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:52 24 4
gpt4 key购买 nike

我正在实现邮箱系统的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com