![](/img/trans.png)
[英]affect only the clicked element in jquery for multiple elements with same class
[英]Set html contents of an element using jQuery but with multiple elements of the same class
如標題所示,我正在嘗試使用jQuery設置元素的html內容。 我將使用的上下文是當用戶將鼠標懸停在表的一行上時。 懸停時將顯示一個彈出窗口,其中包含該行的特定信息。 但是,由於行包含相同的類,jQuery的$()。html()類將僅顯示有關與該類匹配的第一個元素的信息。
這是代碼片段
$(".row").hover(
function() {
$(".popup").html(
$(".content-to-be-displayed").html()
);
$(".popup").show();
$(window).on("mousemove.tooltip", function(e) {
var x = (e.clientX + 20) + 'px',
y = (e.clientY + 20) + 'px';
$(".popup").css({
top: y,
left: x,
});
});
},
function() {
$(".popup").hide();
$(window).off("mousemove.tooltip");
}
);
局部HTML
<tr class= "row">
<div class="content-to-be-displayed" style="display: none;">
<h4>Header:</h4>
<% example_model.example.each do |example| %>
<p>
<%= 'erb plus html content' %>
</p>
<% end %>
</div>
</tr>
模板中的HTML
<%= row do %>
<thead>
</thead>
<tbody>
<div class="popup"></div>
<%= render partial: 'partial', collection: @data %>
</tbody>
<% end %>
使用$(this)和.find的組合
工作示例: https : //jsfiddle.net/osvLs54L/
HTML
<div class="row">
<div class="content-to-be-displayed">
Weee1
</div>
</div>
<div class="row">
<div class="content-to-be-displayed">
Weee2
</div>
</div>
<div class="row">
<div class="content-to-be-displayed">
Weee3
</div>
</div>
<div class="popup">
</div>
JQuery的
$(".row").hover(
function() { $(".popup").html( $(this).find('.content-to-be-displayed').html());}
);
編輯:您的表結構是無效的html,我印象深刻的是您的瀏覽器甚至顯示很多東西。 請閱讀此處了解正確的結構。 https://css-tricks.com/complete-guide-table-element/
在您給出的示例中,僅對初始設置進行了調整,因此它是有效的(將內容添加到元素下的元素
模板中的HTML
<%= row do %>
<thead>
</thead>
<tbody>
<tr>
<td>
<div class="popup"></div>
</td>
</tr>
<%= render partial: 'partial', collection: @data %>
</tbody>
<% end %>
局部HTML
<tr class= "row">
<td>
<div class="content-to-be-displayed" style="display: none;">
<h4>Header:</h4>
<% example_model.example.each do |example| %>
<p>
<%= 'erb plus html content' %>
</p>
<% end %>
</div>
</td>
</tr>
我不確定您要做什么,但我會嘗試一下。 不要使用單獨的彈出元素(可以,但是不干凈)。 嘗試將彈出式數據存儲在data屬性中。
當使用針對多個元素的Selector類時,可以使用this
變量引用當前元素, this
變量指向觸發事件的實際元素-這樣,您可以使用它僅使用其屬性/子元素等。 。
這是一個快速演示: JSnippet演示
HTML:
<table>
<tr class="row" data-popup="Popup Row 1 Data">
<td>Row 1</td>
<td>Hover Me</td>
</tr>
<tr class="row" data-popup="Popup Row 2 Data">
<td>Row 2</td>
<td>Hover Me</td>
</tr>
<tr class="row" data-popup="Popup Row 3 Data">
<td>Row 3</td>
<td>Hover Me</td>
</tr>
</table>
<div class="popup"></div>
JS:
$(function(){
$(".row").hover(
function() {
var $this = $(this);
$(".popup").text($this.data("popup"));
$(".popup").css({
top: $this.offset().top,
left: $this.offset().left + $this.width() + 5,
width: $this.width()
}).show();
},
function() {
$(".popup").hide();
}
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.