2017-02-21 65 views
0

我正在尋找交換元素的內容與div中另一個元素的內容。點擊一下,與頂級項目交換項目

我創建了一個小提琴,但有幾個問題:

https://jsfiddle.net/2o3u0366/

$('.value').click(function(){ 
var newValue = $(this).text(); 
$(this).replaceWith($('.header').text()); 
$('.header').text(newValue); 
}); 

<div class="dropdown"> 
<h2 class="header">This</h2> 
<h2 class="value">That</h2> 
<h2 class="value">Three</h2> 
<h2 class="value">Four 
</h2> 
</div> 
<div class="dropdown"> 
<h2 class="header">This</h2> 
<h2 class="value">That</h2> 
<h2 class="value">Three</h2> 
<h2 class="value">Four</h2> 
</div> 

我期待有它來自的div元素目前在拉,你可以在例子中看到,它是從同一個班的每個div中拉出來的。我無法弄清楚放置「THIS」語句的位置,或者我如何遍歷DOM以使此功能起作用。

任何幫助或建議將不勝感激,謝謝!

+0

喜歡這個? https://jsfiddle.net/axo8d65c/ –

回答

0

一種方法是使用.closest()上到包含div,然後.find()獲取該div中的標題項。還請注意,您不需要.replaceWith(),因爲您只是想設置文本。在下面的代碼中,我創建了引用當前項目和標題的變量,以便通過使用相同的選擇器重複調用$()來保存。

$('.value').click(function(){ 
 
    var $this = $(this); 
 
    var $header = $this.closest(".dropdown").find('.header'); 
 
    var newValue = $this.text(); 
 
    $this.text($header.text()); 
 
    $header.text(newValue); 
 
});
.dropdown { float: left; margin-right: 100px; } 
 
.dropdown:first-of-type { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="dropdown"> 
 
<h2 class="header">This</h2> 
 
<h2 class="value">That</h2> 
 
<h2 class="value">Three</h2> 
 
<h2 class="value">Four 
 
</h2> 
 
</div> 
 
<div class="dropdown"> 
 
<h2 class="header">This</h2> 
 
<h2 class="value">That</h2> 
 
<h2 class="value">Three</h2> 
 
<h2 class="value">Four</h2> 
 
</div>