改变div的内容 - jQuery

Oli*_*sen 78 jquery

如果单击其中一个LINKS,如何更改此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>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 138

您可以为链接订阅.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;
});
Run Code Online (Sandbox Code Playgroud)

但请注意,如果替换此div的内容,则将销毁已分配的单击处理程序.如果您打算在div中注入一些需要附加事件处理程序的新DOM元素,则应在插入新内容后在.click处理程序内执行此附件.如果保留了事件的原始选择器,您还可以查看.delegate附加处理程序的方法.

  • @Oliver'Oli'Jensen,像这样:`$('#content-container').html($('#someOtherDivId').html());` (2认同)

Jos*_*ber 14

你需要在这里使用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();
});
Run Code Online (Sandbox Code Playgroud)

如果您只想在div中添加内容,而不是替换其中的所有内容,则应使用append:

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

如果您希望新添加的链接在单击时也添加新内容,则应使用事件委派:

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


Jør*_*gen 5

$('a').click(function(){
 $('#content-container').html('My content here :-)');
});
Run Code Online (Sandbox Code Playgroud)