2013-07-29 30 views
1

這應該很簡單。基本上,當單擊列表中的項目時,將文本插入/替換到目標div中。 'replaceWith'可能不是要使用的東西,因爲它會刪除原始數據。 另外,如何將「selected」類添加到目標div中的文本。更改文本div onClick列表中的項目

反正這裏是我到目前爲止有:http://jsfiddle.net/BM8Cb/

HTML

<div class="selected" id="here"> 
    <li>All</li> 
</div> 
<hr> 
<ul> 
    <li>All</li> 
    <li>Category 1</li> 
    <li>Category 2</li> 
    <li>Category 3</li> 
</ul> 

CSS

ul {list-style:none;padding:0; margin:0;} 
li {cursor:pointer;} 
li:hover {color:red;} 
.selected {color:red;} 

JS

$("li").click(function() { 
    $("#here").replaceWith(this); 

});

感謝您的幫助

+0

嘗試[HTML()](http://api.jquery.com/html/)和[addClass()](HTTP:// API。 jquery.com/addClass/)。 –

+0

LI元素不能是DIV的子元素嗎? – adeneo

+0

http://jsfiddle.net/BM8Cb/2/ – adeneo

回答

1

什麼

$("li.item").click(function() { 
    $("#here").html($(this).html()); 
}); 

如果你所需要的只是文字。

0

改變你的JS到:

$("li.item").click(function() { 
    var item = $(this).clone(); 
    item.attr("class","selected"); 
    $(".selected").append(item)  
    $(this).hide(); 
}); 

這裏的小提琴:http://jsfiddle.net/J7JST/2/

這也將所選類添加到您的項目

0

使用replaceWith將替換DOM節點,以便下次嘗試時不再存在。你需要使用append

$("#here").append(this); 

和通過使用'this'你是複製一切包括事件處理程序。如果你想只是文本,你可以這樣做

$("#here").append(this.innerHTML); 
+0

追加它會在每次添加文本,而不是替換它 – user1234