2011-08-21 16 views
54

リンクの1つをクリックすると、このdivの内容をどのように変更できますか?あなたがリンクについて.clickイベントにサブスクライブし、.html方法使用してdiv要素の内容を変更することができdiv-jQueryの内容を変更します

<div align="center" id="content-container"> 
    <a href="#" class="click cgreen">Main Balance</a> 
    <a href="#" class="click cgreen">PayPal</a> 
    <a href="#" class="click cgreen">AlertPay</a> 
</div> 
+0

類似の質問を参照してください: https://stackoverflow.com/questions/1309452/how-to-replace-innerhtml-of-a-div-using-jquery –

答えて

97

$('.click').click(function() { 
    // get the contents of the link that was clicked 
    var linkText = $(this).text(); 

    // replace the contents of the div with the link text 
    $('#content-container').html(linkText); 

    // cancel the default action of the link by returning false 
    return false; 
}); 

注意をしかし、あなたは、この内容を置き換える場合はクリックをDIVことあなたが割り当てたハンドラは破壊されます。イベントハンドラをアタッチする必要があるdiv内に新しいDOM要素を挿入する場合は、新しいコンテンツを挿入した後でこの添付ファイルを.clickハンドラ内で実行する必要があります。イベントの元のセレクタが保持されている場合は、.delegateメソッドを参照してハンドラをアタッチすることもできます。

+1

他のdivのコンテンツを読み込むにはどうしたらいいですか?同じページで#content-containerに移動しますか? –

+1

@Oliver 'Oli' Jensenのように:$( '#content-container').html($( '#someOtherDivId').html()); ' –

+0

おかげで神!私は#divが.val()で変更できないことに気付きました。代わりに.html()を使用してください。それを機能させるための関数! :D @cuSKありがとう – gumuruh

8

ここで使用する2つのjQuery関数があります。

1)click。これは唯一のパラメータであるため、無名関数をとり、要素がクリックされたときにそれを実行します。

2)html。これは、唯一のパラメータであるhtml文字列を受け取り、要素の内容を提供されたhtmlに置き換えます。

だから、あなたのケースでは、次の操作を行うことになるでしょう:

$('#content-container a').click(function(e){ 
    $(this).parent().html('<a href="#">I\'m a new link</a>'); 
    e.preventDefault(); 
}); 

あなただけにしたい場合は、むしろそれですべてを交換するよりも、あなたのdivにあなたをコンテンツを追加appendを使用する必要があります。

$('#content-container a').click(function(e){ 
    $(this).parent().append('<a href="#">I\'m a new link</a>'); 
    e.preventDefault(); 
}); 

あなたが目をしたい場合eは新しいあなたがevent delegationを使用する必要があり、クリックされたときにも、新しいコンテンツを追加するためのリンクを追加しました:

$('#content-container').on('click', 'a', function(e){ 
    $(this).parent().append('<a href="#">I\'m a new link</a>'); 
    e.preventDefault(); 
}); 
2
$('a').click(function(){ 
$('#content-container').html('My content here :-)'); 
}); 
-2

あなたはreplacewith()

$('.click').click(function() { 
    // get the contents of the link that was clicked 
    var linkText = $(this).text(); 

    // replace the contents of the div with the link text 
    $('#content-container').replaceWith(linkText); 

    // cancel the default action of the link by returning false 
    return false; 
}); 

.replaceWith()方法で同じことをしようとすることができ$('#score_here').html=total;

0

をお試しくださいDOMからコンテンツを削除し、1回の呼び出しで新しいコンテンツをその場所に挿入します。

関連する問題