首页 > 解决方案 > element.firstChild.each() 未定义

问题描述

我无法在页面中捕获 firstChild.each() 元素。

jQuery(function() {
        $(".custom-link").firstChild.each(function(t,x) {
        if (/*$(x).attr('href').indexOf('isbn=' > -1) &&*/ $(x).attr('href').indexOf('isbn=&' == -1)) { //Check if the ISBN exists
        var href = $(x).attr('href');
        var isbn = href.substring((href.lastIndexOf('su=')+3),(href.lastIndexOf('su=')+16));});

我几乎在不同的应用程序中使用了这行代码,具有不同的类,并且运行良好。唯一的区别是 .firstChild 函数,它应该非常简单。

我认为问题可能是在此代码之后加载了类元素,因此我尝试将其包装在 .ready() 函数中,但问题仍然存在。

根据页面来源,页面中有该类的66个实例。

我也尝试使用:

$(".custom-link:first-child").each(function(t,x) {

但是 css :first-child 命令似乎不适用于类选择器。

我尝试创建一个数组并在其上使用 .each() :

var customlinks = $(".custom-link").firstChild;
customlinks.each(function(t,x) {

但我收到“未捕获的类型错误:无法读取未定义的属性‘每个’”,因为 customlinks 仍然未定义。

标签: jqueryclasseach

解决方案


您正在混合使用 jQuery 和 DOM 函数。等效的 jQuery 是:

$(".custom-link > *:first-child").each(...);

您必须将:first-child伪类附加到要选择的元素。.custom-link:first-child选择class="custom-link"本身是其父元素的第一个子元素的元素。> *匹配 的子级.custom-link,然后:first-child将其限制为每个的第一个子级。

您实际上可以将其缩短为

$(".custom-link > :first-child")

因为*那里是默认的。


推荐阅读