无法理解JQuery基础知识

时间:2011-07-16 18:50:09

标签: javascript jquery html

有人可以解释为什么在下面的代码中,必须先调用$(document).ready(function(){ $("#msgid").html(); });才能使用我的appender函数附加到div吗?如果我摆脱那个部分,并按下按钮,没有任何东西被附加到div,这对我来说没有意义!我认为JQuery的.html()方法只返回了div的HTML内容,所以在我的下面的代码中它什么都不会返回,因此服务器没有用处。

CODE:

<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() />

提前致谢!

4 个答案:

答案 0 :(得分:2)

您不需要在函数中包含$(document).ready()。而且,jQuery的主要优点之一是它的事件处理,它允许你停止使用html中的onclick,onmouseoiver属性。

尝试:

    $(document).ready(function(){
        $("#msgid").click(function() {
//This function will be performed whenever the element with id msgid is clicked
 $("#msgid").append("appended by an anonymous function attached to the click event of this element");  
})
        });

OR

 $(document).ready(function(){
        $("#msgid").click('appender');
        });

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

两者都会达到相同的目的,但命名函数会一如既往地保存重复代码。

答案 1 :(得分:2)

<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() />

希望有所帮助

答案 2 :(得分:1)

您可以通过这种方式大大简化代码。

$(function() {
   $('#myButton').click(function() { 
       $("#msgid").append("appended with the appender() function<br />");
       return false;
   });
});

答案 3 :(得分:0)

要做你想做的事,你可以按照以下方式做到

<script type="text/javascript">
$(document).ready(function(){  
    $("#msgid").html('');        //WHY IS THIS CODE BLOCK NECESSARY? to empty the contents of           the div

$("#msgid").click(function() {   
           appender();
        }); // end of click function
 }); // end of document.ready

以下函数的行为类似于全局函数,您可以从任何地方调用它。

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

相关问题