$(document).ready(function()

本文介绍了jQuery中选择器和事件的基本用法,包括页面加载完成后的操作、选择DOM元素的方法、绑定事件处理函数等内容,并通过实例展示了如何利用jQuery简化DOM操作。

$(document).ready(function()

页面加载完成后开始运行do stuff when DOM is ready 中的语句!
    $(document).ready(function() {
       // do stuff when DOM is ready
       });

   选择器
   $(“a”)是一个jquery的选择器(selector)
   $("")其中的字段就是元素的标记。比如$("div")就是<div></div>
   click是函数对象的一个方法。方法为点击鼠标事件!
     例:
     $(document).ready(function() {
     $("a").click(function() {
        alert("Hello world!");
         });
       });

   $("div").click $("div")就是页面中所有的 div标签 这句话就是给所有的标签为div的元素 绑定了一个click事件 即当所有div 被鼠标单     击的时候 执行 alert("Hello World!");


   选择器(selector)和事件(events)
   选择DOM元素
   选择一个ID为orderedlist的元素,相当于javascript中的document.getElementById("orderedlist"),jquery中只需要$("#id")其中的id为元素的ID,元素为任意元素!addClass为把这个元素的css的class改为red
   $(document).ready(function() {
    $("#orderedlist").addClass("red");
   });

       $("#id > xx") 这种表示ID的元素下的所有元素标记为xx的元素设置CSS的Class, id为元素的id xx为元素的标记例<div><li><a>等!
      $(document).ready(function() {
         $("#orderedlist > li").addClass("blue");
        });

$(document).ready(function() {
// use this to reset a single form
$("#reset").click(function() {
       $("#form")[0].reset();
});
});
 



这个代码只是ID为form的表单执行reset()方法。但是万一你有很多个表单需要执行呢?那么你可以这样写:
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
       $("form").each(function() {
         this.reset();
       });
});
});

另外一个你必须面对的问题是选择某个或某几个元素。Jquery提供了filter()和not()方法。当filter()是过滤一些适合filter()表达式元素,而not()是删除和not()表达式相反的元素。当你想选择所有的li元素,并且不包含ul子元素呢?你可以这样写:
$(document).ready(function() {
$("li").not("[ul]").css("border", "1px solid black");
});

find(expr) 在匹配的对象中继续查找符合表达式的对象 
<p>Hello</p><p id="a">Hello Again</p><p class="selected">And Again</p>

Query代码及功能: 
function jq(){
    alert($("p").find("#a").html())
}
在$("p")对象中查找id为a的对象

存疑:

结果是除了包含ul子元素的li,其他所有的li都得到了一个border.可能你也想选择有name属性的anchor(<a>):
$(document).ready(function() {
$("a[@name]").background("#eee");
});
 



要匹配属性的值(value),我们可以用”*=”来代替”=”
$(document).ready(function() {
$("a[@href*=/content/gallery]").click(function() {
       // do something with all links that point somewhere to /content/gallery
});
});
 



直到现在,我们已经学到了很多选择器的使用。这里还有种情况你需要选择前一个或后一个元素。想一想starterkit.htm里的FAQ,当你click问题的时候,它是怎么实现隐藏和显示的呢?代码是这样的:
$(document).ready(function() {
$('#faq').find('dd').hide().end().find('dt').click(function() {
      var answer = $(this).next();
      if (answer.is(':visible')) {
         answer.slideUp();
      } else {
         answer.slideDown();
      }
    });
});
 



因为上面只有唯一一个选择器(#faq),我们用chain来减少代码的长度和提高代码的易读性和表现性.这里要说明一下,如果按原文翻译过来我想很多人都看不懂,感觉他自己也没怎么说明白。我说说我自己的理解:
‘dd’和‘dt’都是#faq的子元素,find()的作用就是找到它的子元素。End()应该和next()搭配的,end()实质上是把 ‘dd’过滤了,也就是next()的时候实质上是参考的’dt’。这样每个’dt’的next就是‘dd’,挺容易实现的。要是还不明白你可以边参考边照着做一遍。

除了同属元素外,我们也可以选择父元素:
$(document).ready(function() {
$("a").hover(function() {
       $(this).parents("p").addClass("highlight");
}, function() {
       $(this).parents("p").removeClass("highlight");
});
});
 


很容易看懂,p就是a的父元素。

 

(document)意思是说,获取整个网页文档对象(类似的于window.document),$(document).ready意思就是说,获取文档对象就绪的时候。

$(document).ready(function() {
// do stuff when DOM is ready//当文档载入后从此处开始执行代码
});

你提供的这段 JavaScript 代码的作用是: > **实现 radio 按钮的“可取消选中”功能**,即: > - 如果 radio **未选中**,点击后选中; > - 如果 radio **已经选中**,再次点击会取消选中。 --- ## ✅ 代码解析 ```js $(document).ready(function() { $('input:radio').click(function() { var $radio = $(this); if ($radio.data('waschecked') == true) { $radio.prop('checked', false); $radio.data('waschecked', false); } else { $radio.prop('checked', true); $radio.data('waschecked', true); } }); }); ``` ### 🔍 分析每一步 1. `$(document).ready(...)` - 确保页面 DOM 加载完成后才执行代码。 2. `$('input:radio').click(function() {...})` - 为页面上所有 `<input type="radio">` 元素绑定 `click` 事件。 3. `var $radio = $(this);` - 获取当前点击的 radio 按钮的 jQuery 对象。 4. `if ($radio.data('waschecked') == true)` - 使用 jQuery 的 `.data()` 方法判断这个 radio 是否曾经被点击过(即是否“已选中”)。 5. 如果是“已选中”,则: ```js $radio.prop('checked', false); $radio.data('waschecked', false); ``` - 取消选中; - 更新状态为“未选中”。 6. 如果是“未选中”,则: ```js $radio.prop('checked', true); $radio.data('waschecked', true); ``` - 设置为选中; - 更新状态为“已选中”。 --- ## ⚠️ 存在的问题 虽然这段代码逻辑看起来合理,但它存在几个**严重问题**,可能导致你之前遇到的 radio **无法正常选中**的问题: ### ❌ 问题 1:**手动干预了浏览器的默认行为** - `click` 事件发生时,浏览器**已经处理了默认行为**(即选中 radio); - 但你又手动设置了 `prop('checked')`,可能会导致冲突。 ### ❌ 问题 2:**radio 组的互斥性被破坏** - radio 按钮通常是**一组中只能选一个**; - 但你用了 `data('waschecked')` 控制状态,可能导致: - 一个 radio 被取消选中; - 但组内其他 radio **没有被自动取消选中**; - 导致多个 radio 同时处于“已选中”状态 ❌ --- ## ✅ 推荐改进方案 ### ✅ 改进思路: - 使用 `click` 事件; - **允许默认行为执行**; - 使用 `setTimeout(..., 0)` 延迟处理“取消选中”; - 避免干扰 radio 组的互斥性; ### ✅ 改进后的代码: ```js $(document).ready(function () { $(document).on('click', 'input[type="radio"]', function () { const $radio = $(this); const name = $radio.attr('name'); const isChecked = $radio.prop('checked'); // 如果点击的是已经选中的 radio,则取消选中 if (isChecked) { setTimeout(() => { $radio.prop('checked', false); }, 0); } console.log("Radio clicked:", name, $radio.val()); }); }); ``` --- ## ✅ 示例 HTML ```html <label><input type="radio" name="group1" value="1"> 选项1</label> <label><input type="radio" name="group1" value="2"> 选项2</label> <label><input type="radio" name="group1" value="3"> 选项3</label> ``` --- ## ✅ 效果说明 | 操作 | 行为 | |------|------| | 第一次点击某个 radio | 正常选中 ✅ | | 再次点击同一个 radio | 取消选中 ✅ | | 点击另一个 radio | 当前选中项取消,新项选中 ✅ | --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值