有人可以解释为什么在下面的代码中,必须先调用$(document).ready(function(){ $("#msgid").html(); });,然后才能使用appender函数将其附加到div吗?如果我放弃了该部分,然后按了按钮,则div不会附加任何内容,对我而言这没有意义!我以为JQuery的.html()方法只是返回div的HTML内容,因此在我的以下代码中,它将什么也不返回,因此对服务器没有任何作用。

码:

<script type="text/javascript">
$(document).ready(function(){
    $("#msgid").html();        //WHY IS THIS CODE BLOCK NECESSARY?
    });

function appender(){
    $(document).ready(function(){
    $("#msgid").append("appended with the appender() function<br />");
    });
}
</script>

This is Hello World by HTML

<div id="msgid">
</div>

<input type="button" id="myButton" value="click me" onclick=appender() />


提前致谢!

最佳答案

<script type="text/javascript">
    $(document).ready(function(){
        $("#msgid").html("");        //This is to clear the html code that is inside #msgid
        });

    function appender(){
        $("#msgid").append("appended with the appender() function<br />");
        });
    }
    </script>

    This is Hello World by HTML

    <div id="msgid">
    </div>

    <input type="button" id="myButton" value="click me" onclick=appender() />


希望能有所帮助

09-25 21:08