jQuery的第一个孩子“这个”
我试图将“this”从单击的跨度传递给一个jQuery函数,然后可以在该单击的元素的第一个子元素上执行jQuery。 似乎无法得到正确的…
<p onclick="toggleSection($(this));"><span class="redClass"></span></p> 使用Javascript:
 function toggleSection(element) { element.toggleClass("redClass"); } 
我如何引用:元素的第一个孩子?
如果您想将select器应用于现有jQuery集提供的上下文,请尝试find()函数 :
 element.find(">:first-child").toggleClass("redClass"); 
JørnSchou-Rode指出,你可能只想findcontext元素的第一个直接后裔 ,因此也就是子select符 (>)。 他还指出 ,你可以使用children()函数 ,它非常类似于find(),但只search层次结构中的一个深度(这就是你所需要的):
 element.children(":first").toggleClass("redClass"); 
 使用children函数 :firstselect element第一个子element : 
 element.children(":first").toggleClass("redClass"); 
我已经添加了jsperftesting,以查看不同方法的速度差异,以获得第一个孩子(总共超过1000个孩子)
 给定, notif = $('#foo') 
jQuery方法:
-   $(":first-child", notif)– 4304 ops / sec – 最快
-   notif.children(":first")– 653 ops / sec – 慢了85%
-   notif.children()[0]– 1416 ops / sec – 慢了67%
原生方式:
-   JavaScript原生' ele.firstChild– 4,934,323 ops /秒(所有上述方法比firstChild慢100%)
-   jQery的原生DOM ele:notif notif[0].firstChild– 4,913,658 ops / sec
 所以,前3个jQuery方法是不推荐的,至less对于第一个孩子(我怀疑其他许多人也是如此)。 如果你有一个jQuery对象,并需要获得第一个孩子,然后使用数组引用[0] (推荐)或.get(0)并使用ele.firstChild从jQuery对象获取本地DOM元素 。 这给出了与常规JavaScript使用相同的结果。 
所有testing都在Chrome Canary build v15.0.854.0中完成
 element.children().first(); 
find所有的孩子,并得到他们的第一个。
你有没有尝试过
 $(":first-child", element).toggleClass("redClass"); 
我想你想把你的元素设置为你的search的上下文。 有可能是一个更好的方法来做到这一点,其他一些jQuery的大师将在这里跳进去,扔给你:)
 我刚刚编写了一个插件,如果可能的话,它使用.firstElementChild如果需要的话,可以退回到遍历每个单独的节点: 
 (function ($) { var useElementChild = ('firstElementChild' in document.createElement('div')); $.fn.firstChild = function () { return this.map(function() { if (useElementChild) { return this.firstElementChild; } else { var node = this.firstChild; while (node) { if (node.type === 1) { break; } node = node.nextSibling; } return node; } }); }; })(jQuery); 
它不像纯DOM解决scheme那么快,但是在Chrome 24下的jsperftesting中 ,它比任何其他基于jQueryselect器的方法快几个数量级。
请像这样使用它首先给一个类名称标签p像“myp”
然后使用下面的代码
 $(document).ready(function() { $(".myp").click(function() { $(this).children(":first").toggleClass("classname"); // this will access the span. }) }) 
这可以用这样一个简单的魔法来完成:
 $(":first-child", element).toggleClass("redClass"); 
参考: http : //www.snoopcode.com/jquery/jquery-first-child-selector
如果你想立即第一个孩子,你需要
  $(element).first(); 
如果你想从你的元素的dom特定的第一个元素,然后使用下面
  var spanElement = $(elementId).find(".redClass :first"); $(spanElement).addClass("yourClassHere"); 
试试: http : //jsfiddle.net/vgGbc/2/