用jquery预处理html的一种方法有效,但为什么另一种方法无效't

One way of prepending html with jquery works but why the other way doesn't?

本文关键字:方法 另一种 为什么 无效 有效 html 预处理 一种 jquery      更新时间:2023-09-26

这种预处理方式对我有效:

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $("#learn-more-button").click(function() {
                $("#main-text").load('ajax/learn-more.html #learn-more', function() {
                                            $(this).prepend('<p> DARN </p>'); // <=== This here WORKS
                    $(this).hide().fadeIn(500); //Fade in
                    $("#main-text").animate({ // Then Animate
                        width:"500px",
                        left:'+=400px',}, 
                        400
                    );                                                                  
                });                 
            });
        });
    </script>

这种准备方式对我不起作用:

   <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $("#learn-more-button").click(function() {
                $("#main-text").prepend('<p> DARN </p>'); // <=== This here doesn't work
                $("#main-text").load('ajax/learn-more.html #learn-more', function() {
                    $(this).hide().fadeIn(500); //Fade in
                    $("#main-text").animate({ // Then Animate
                        width:"500px",
                        left:'+=400px',}, 
                        400
                    );                                                                  
                });                 
            });
        });
    </script>

为什么第二种方法不起作用?应该如何使其发挥作用?

我不是一个真正的jQuery的人,所以很感激你的帮助:)

执行load()时,#main-text元素的内容将被完全替换。因此,如果像第二种方法那样在load之前添加<p>DARN</p>,它就会被覆盖。

在第一种方法中,<p>被添加到负载的回调函数中。这是在加载完成后调用的。

您还应该将方法链接到一个选择器上以获得更好的性能,例如:

<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $("#learn-more-button").click(function() {
            $("#main-text").load('ajax/learn-more.html #learn-more', function() {
                $(this).prepend('<p> DARN </p>')
                    .hide().fadeIn(500)
                    .animate({
                        width:"500px",
                        left:'+=400px'
                    }, 400);
            });                 
        });
    });
</script>