更改div的内容-jQuery


Answers:


156

您可以订阅链接的.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
然后,如何将同一页面上另一个div的内容加载到#content-container中?
奥利弗·奥利·詹森

2
@Oliver'Oli'Jensen,例如:$('#content-container').html($('#someOtherDivId').html());
Darin Dimitrov

感谢上帝!我意识到#div不能通过.val()更改;函数,我们应该使用.html(); 使它起作用的功能!:D @cuSK谢谢
gumuruh 2015年

现场保护@DarinDimitrov
excitedmicrobe

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

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

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

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

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

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

2

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


1

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

查看更多@使用jQuery更改div的内容

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.