javascript中$(function() {....}) 是 jquery 中的经典用法,等同于 $(document).ready(function() {....}),即在页面加载完成后才执行某个函数,如果函数中要操作 dom,在页面加载完成后再执行会更安全,所以在使用 jquery 时这样的写法很常见。
$(document).ready() 里的代码是在页面内容都加载完才执行的,如果把代码直接写到script标签里,当页面加载完这个script标签就会执行里边的代码了,此时如果你标签里执行的代码调用了当前还没加载过来的代码或者dom,那么就会报错,当然如果你把script标签放到页面最后面那么就没问题了,此时和ready效果一样。
$(document).ready(function(){})可以简写成$(function(){});
点击段落后,此段落隐藏:
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1673">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680447514234.jpg" alt="LanguagePro">
</a>
<div class="aritcle_card_info">
<a href="/ai/1673">LanguagePro</a>
<p>LanguagePro是一款强大的AI写作助手,可以帮助你更好、更快、更有效地写作。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="LanguagePro">
<span>120</span>
</div>
</div>
<a href="/ai/1673" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="LanguagePro">
</a>
</div>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
</body>
</html> 如果把$(document).ready(function() {});去掉后,无法隐藏段落:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("p").click(function(){
$(this).hide();
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
</body>
</html> 但是把script放到页面最后的话,就可恢复隐藏效果:
<html>
<head>
</head>
<body>
<p>If you click on me, I will disappear.</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
</body>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$("p").click(function(){
$(this).hide();
});
</script>
</html> javascript 中(function(){})()的作用和用法有哪些
和对象啥的没关系
(function(){})() 代表立即执行一个匿名的方法
一般用来与外界隔绝 制造一个似闭包的环境 创建一个作用域链 避免变量冲突
(function(){
var a;
..........
})()
这篇文章主要介绍了javascript中$(function() {});写与不写有哪些区别,希望对大家有所帮助。
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号