当单击其中一个链接时,如何更改此div的内容?
<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>
发布于 2011-08-21 23:35:50
您可以订阅链接的.click事件,并使用.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
方法以附加处理程序。
发布于 2011-08-21 23:37:09
$('a').click(function(){
$('#content-container').html('My content here :-)');
});
发布于 2018-01-05 14:30:18
您可以尝试使用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中删除内容并在其位置插入新内容。
https://stackoverflow.com/questions/7139208
复制相似问题