簡體   English   中英

javascript彈出數據被覆蓋

[英]javascript popup data getting overwritten

每當用戶將鼠標懸停在鏈接上時,我都會使用javascript來顯示彈出窗口,我有一個鏈接列表。彈出窗口將包含一些與鏈接相關的數據。 每當我將鼠標懸停在鏈接上時,數據就會彈出,但這是列表的最后一條記錄。 如何獲取與鏈接相關的數據?

誰能幫幫我嗎?

謝謝。

請在下面找到代碼

Javascript:

<script type="text/javascript">
        $(function() {
      var moveLeft = 20;
      var moveDown = 10;

      $('#web'+'<%= website.id%>').hover(function(e) {
        $('div.pop-up').show();
      }, function() {
        $('div.pop-up').hide();
      });

      $('#web'+'<%=website.id%>').mousemove(function(e) {
        $("div.pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
      });

    });
    </script>

HTML:

<% for website in @websites %>
<tr>
    <td class="website" id="web_<%= website.id%>"><%= link_to h(truncate(website.name, :length => 30)), website_path(website) %></td>
    <td><%= website_status_image(website) %></td>
</tr>
  <div class="pop-up">
    <h3>Pop-up div Successfully Displayed</h3>
    <p><%= website.name%></p>
  </div>
<% end %>

您的頁面上有很多彈出窗口,而jQuery不知道您要顯示哪一個,並顯示最后一個(來自集合)。 另外,您不應該在<td>標簽之外放置任何html標簽。

有很多方法可以實現此功能。 您應該使用jQuery( .closest() .parent()方法)找到彈出窗口。 這是修改后的代碼:

html

    <tr>
     <td class="website"><%= link_to h(truncate(website.name, :length => 30)), website_path(website) %>
       <div class="pop-up" style='display: none;'>
        <h3>Pop-up div Successfully Displayed</h3>
        <p><%= website.name%></p>
       </div>
     </td>
    <td><%= website_status_image(website) %></td>
</tr>

js

$('.website').hover(function(e) {
    $('div.pop-up', this).show();
  }, function() {
    $('div.pop-up', this).hide();
  });

如果將您的網站名稱放入<tr>標記中的html data-attribute中,在表旁邊創建一個彈出div,然后在每次用戶懸停鏈接時將此數據放在彈出窗口中,效果會更好。

html

<table>
    <% for website in @websites %>
    <tr>
    <td class="website" data-name='<%= website.name%>'><%= link_to h(truncate(website.name, :length => 30)), website_path(website) %></td>
    <td><%= website_status_image(website) %></td>
    </tr>
    <% end %>
</table> 

...

<div class="pop-up" style='display: none;'>
    <h3>Pop-up div Successfully Displayed</h3>
    <p></p>
</div>

js

$('.website').hover(function(e) {
        var popup = $('div.pop-up').show();
        $('p', popup).html($(this).data('name'));
      }, function() {
        $('div.pop-up').hide();
      });

但我建議您使用jQuery插件或bootsrap popover

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM