【问题标题】:Make Div tag clickable使 div 标签可点击
【发布时间】:2014-07-15 23:22:17
【问题描述】:

嗨,下面的代码给了我表格行格式的消息列表,我想让每一行都可以点击。我已经尝试了 SO 中的每一个建议,但无法使其发挥作用。
由于我无法使整个 tr 可点击,我将 i.reason 字段设置为可点击的临时解决方案。

<% if @notifyCount > 0 %>
<table class="table table-hover table-condensed">
<% @notify.each do |i| %>
<tr class="notifyTable" id= "<%=i.id %>">
 <td class="myWidth concat"> 
    <%= image_tag "#{i.incident_image}", style: "height:45px; width:45px; float:left; margin: 0 8px 0 0" %> <b> <%= i.sender.first_name + ' ' + i.sender.last_name %> </b> <br> 
    <div> <%= link_to truncate(i.reason.capitalize, length: 50), message_member_path(id: i.id), style: "text-decoration:none" %> </div>
 </td>
</tr>
<%end%>
</table>
<%else%>
<p style="opacity:0.7;text-align:center;margin-top:5px"> No Unread Messages ...</p>
<%end%>

【问题讨论】:

    标签: jquery ruby-on-rails jquery-ui twitter-bootstrap


    【解决方案1】:

    JS

    你必须使用 Javascript 来完成这项工作

    Javascript(和 JQuery)基本上工作在浏览器的前端(在DOM - Document Object Model 内)将事件绑定到页面上的元素。

    以下是使用 JQuery 使 div “可点击”的方法:

    #app/assets/javascripts/application.js
    $(document).on("click", ".div", function() {
       // Your Action Here
    });
    

    --

    关于您的问题的具体细节,您可能需要查看使用以下代码:

    #app/assets/javascripts/application.js
    $(document).on("click", ".notifyTable", function(){
       alert("Row is clicked");
    });
    

    这将允许您捕获点击事件。如果您想通过该点击执行操作,最好将data 属性添加到您的row,如下所示:

    <tr class="notifyTable" id= "<%=i.id %>" data-link="http://google.com">
    

    这将允许您这样做:

    #app/assets/javascripts/application.js
    $(document).on("click", ".notifyTable", function(){
       window.location.href = $(this).data("link")
    });
    

    【讨论】:

    • 我喜欢这种方法,但我想在单击表格行时导航到 message_member_path(id: i.id) 路径(类似于我在 &lt;%= link_to truncate(i.reason.capitalize, length: 50), message_member_path(id: i.id), style: "text-decoration:none" %&gt; 上按下的链接)以导航到特定对象。
    • 我正在尝试像data-link= message_view_member_path(&lt;%=i.id%&gt;),但它以文本形式显示No route matches [GET] "/users/message_view_member_path(2144)",在这种方法中,它不会将鼠标指针显示为可点击吗?它只会显示为指针,用户不会理解它是否可点击。
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 2016-10-09
    • 2023-01-28
    • 1970-01-01
    • 2020-10-07
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多