Trouble Understanding JQuery fundamentals
Can someone explain why in the below code, $(docume开发者_开发技巧nt).ready(function(){ $("#msgid").html(); });
must be called before I can append to the div with my appender function? If I get rid of that part, and press the button, nothing gets appended to the div, this doesn't make sense to me! I thought JQuery's .html() method just returned the HTML contents of the div, so in my below code it would return nothing, and therefore server no purpose.
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() />
Thanks in advance!
<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() />
Hope that helps
You do not need to have the $(document).ready() inside your function. But also, one of the main benefits of jQuery is its event handling, which allows you to stop using the onclick, onmouseoiver attributes in html.
Try:
$(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 />");
}
Both will achieve the same end, but naming a function saves repeating code as always.
You can greatly simplify your code this way.
$(function() {
$('#myButton').click(function() {
$("#msgid").append("appended with the appender() function<br />");
return false;
});
});
To do what you want , you can do as below
<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
The below functions behaves like a global function and you can call it from anywhere.
function appender(){
$("#msgid").append("appended with the appender() function<br />");
}
精彩评论