this和 $(this)的区别

来源:互联网 发布:淘宝上哪家卖玉的店铺 编辑:程序博客网 时间:2024/05/19 02:42

今天在使用jquery来实现一个小功能的时候,发现了一个小问题,故在这里总结一下,供以后学习》


问题:this 和 $(this)的区别

1.this 指的是html 对象

2.$(this) 指的是jquery对象


在使用$(this) 的时候要放到 $(function (){

$(this) 要写到这里。

});

下面来看一个例子:

$(function(){$(".choice1").click(function(){//$(this) 的用法  必须写到$(function(){}); 中 否则不生效var slideIndex = $(this).parent().parent().parent().attr("name");var choiceIndex = $(this).attr("name");alert("slideIndex:"+slideIndex);alert("choiceIndex:"+choiceIndex);});$(".choice2").click(function(){//$(this) 的用法  必须写到$(function(){}); 中 否则不生效var slideIndex = $(this).parent().parent().parent().attr("name");var choiceIndex = $(this).attr("name");alert("slideIndex:"+slideIndex);alert("choiceIndex:"+choiceIndex);});$(".choice3").click(function(){//$(this) 的用法  必须写到$(function(){}); 中 否则不生效var slideIndex = $(this).parent().parent().parent().attr("name");var choiceIndex = $(this).attr("name");alert("slideIndex:"+slideIndex);alert("choiceIndex:"+choiceIndex);});});


文中 的

$(this) 的时候要放到 $(function (){

$(this) 要写到这里。

});

如果把代码改成是这样:

$(function(){$(".choice1").click(function(){choice1();});});function choice1(){//$(this) 的用法  必须写到$(function(){}); 中 否则不生效var slideIndex = $(this).parent().parent().parent().attr("name");var choiceIndex = $(this).attr("name");alert("slideIndex:"+slideIndex);alert("choiceIndex:"+choiceIndex);}

这样写就不对了 就回去不到$(this) 对象了  不知道为什么,现在这记录一下,以后有机会把它弄明白





原创粉丝点击