jquery - 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 仍然未定义。
解决方案
您正在混合使用 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")
因为*
那里是默认的。
推荐阅读
- prestashop-1.7 - 我正在使用 prestashop 1.7.5.2 一些客户想要从他们的商店中删除他们只想使用购物车功能的付款选项
- python - 为什么 scipy.optimize 参数上的误差线会超出范围
- vue.js - v-选择多个未设置值
- r - 未来的系统命令/Rshiny 中的承诺
- mongodb - 是否可以使用颤振飞镖连接到本地 MongoDB?
- android - 如何将徽章值添加到 android tabview?
- webpack - 如何在运行时从 webpack 构建的包中需要外部 commonjs 模块
- java - java - 如何使用json-simple将2个二维数组写入java中的json对象?
- mysql - 如果列为空,如何在使用 CONCAT_WS 时停止在数据库字段中添加逗号
- unity3d - 将程序集从“Temp/Assembly-CSharp.dll”复制到“Library/ScriptAssemblies/Assembly-CSharp.dll”失败 UNITY3D 错误