首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >更改div - jQuery的内容

更改div - jQuery的内容
EN

Stack Overflow用户
提问于 2011-08-21 23:33:32
回答 5查看 312.6K关注 0票数 100

当单击其中一个链接时,如何更改此div的内容?

代码语言:javascript
复制
<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>
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-08-21 23:35:50

您可以订阅链接的.click事件,并使用.html方法更改div的内容:

代码语言:javascript
复制
$('.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方法以附加处理程序。

票数 168
EN

Stack Overflow用户

发布于 2011-08-21 23:37:09

代码语言:javascript
复制
$('a').click(function(){
 $('#content-container').html('My content here :-)');
});
票数 5
EN

Stack Overflow用户

发布于 2018-01-05 14:30:18

您可以尝试使用replacewith()进行相同的操作

代码语言:javascript
复制
$('.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中删除内容并在其位置插入新内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7139208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档