将.append()与click()一起使用

Using .append() with click()

本文关键字:一起 append click      更新时间:2023-09-26

你好,我想在用户点击div时替换它中的文本。我已经尝试过这个代码,但我的代码有问题

<script>
$(document).ready(function(){
    //alert('hi');
    $('div').append('hi')
    $('div').click(function(){
        $('this').append('how r u');
        })
    })
</script>

请帮助

感谢

你很接近!

this是JavaScript中的一个关键字,但您将其用作字符串。在this周围去掉',你就应该没事了!

$('div').click(function(){
    $(this).append('how r u');
});

注意

如果要替换文本,则应使用.html().text()而不是.append()。Append将使div中的所有文本保持原样,并在末尾添加新文本。

如果要替换文本,请使用html方法

$('div').click(function(){
        $(this).html('how r u');
        })    
})

你不需要'this

工作样品:http://jsfiddle.net/4xj72/1/

如果没有添加HTML标记,也可以使用text()方法。

http://jsfiddle.net/4xj72/3/

    <script>
$(document).ready(function(){
    //alert('hi');
    $('div').append('hi')
    $('div').click(function(){
        $(this).append('how r u');
        })
    })
</script>

$('this').append('how r u');应为$(this).append('how r u');this是一个关键字,它周围不应该有'引号。