2011-08-21 127 views
54

如何在單擊某個鏈接時更改此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

你可以認購的鏈接。點擊該事件,並使用.html方法改變div的內容:

$('.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(); 
}); 

如果你想要個Ë新添加的鏈接點擊時還要添加新的內容,你應該使用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

嘗試$('#score_here').html=total;

0

您可以在同一嘗試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()方法從DOM中刪除內容,並通過一次調用將新內容插入其位置。