سؤال

I'm curious why the code bellow displays "Why this text appears on load" on the page?

<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(function() {
    $('<h4>Why this text appears on load</h4>').click(function() {
        alert('3');
    }).insertAfter($('h1'));
});
</script>
</head>
<body>
    <h1>H</h1>
</body>
</html>
هل كانت مفيدة؟

المحلول 2

$(function(){}) is shorthand for $(document).ready(function(){}). So, when the document (the DOM) is ready, your code runs.

You create an <h4> element, assign a click handler to it, then append it after each <h1> on the page.

نصائح أخرى

In jquery.js, jQuery is listening for the DOM to be ready by either using the DOMContentLoaded event, or the document.onreadystatechange event. Once the dom is ready, all callbacks that have been passed to .ready() are triggered, and any calls to .ready() that come after that are immediately executed.

Note: $(function(){}) is equivalent to $(document).ready(function(){})

$('<h4>Why this text appears on load</h4>') is inserted after insertAfter($('h1')); on document.ready()

$(function() {}) is short form of document.ready(function() {}) which is executed as soon as the html element in the page are available.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top