改变div的内容 - jQuery

时间:2011-08-21 15:33:32

标签: 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>

6 个答案:

答案 0 :(得分:128)

您可以订阅链接的.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方法。

答案 1 :(得分:13)

您需要在这里使用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 :(得分:4)

$('a').click(function(){
 $('#content-container').html('My content here :-)');
});

答案 3 :(得分:1)

您可以使用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中删除内容,并通过一次调用在其位置插入新内容。

答案 4 :(得分:1)

尝试使用jQuery更改div的内容。

查看更多@ Change content of div using jQuery

$(document).ready(function(){
    $("#Textarea").keyup(function(){
        // Getting the current value of textarea
        var currentText = $(this).val();

        // Setting the Div content
        $(".output").text(currentText);
    });
});

答案 5 :(得分:-1)

尝试$('#score_here').html=total;

相关问题