gpt4 book ai didi

javascript - 为什么我会收到未定义的 'children' 电话?

转载 作者:行者123 更新时间:2023-11-29 17:46:48 27 4
gpt4 key购买 nike

我试图在单击导航中的某个按钮后将一个类附加到 div。

$navButtons.on('click', navigationClick);

// liseten to the navigation and add a class to the link that was selected
var $navButtons = $('nav a');

var $currentListItem = $('nav li')

function navigationClick(){
console.log("click");

// if there is a class to remove, remove it
// currentListItem.children('div').removeClass("nav-selected");

var index = $navButtons.index(this);
console.log(index);

$currentListItem = $currentListItem[index];

console.log($currentListItem); = <li>
$currentListItem.children('div').addClass("nav-selected");
}

当我尝试执行此代码时出现错误:

Cannot read property .children' of undefined.

我不确定为什么它说 $currentListItem 是未定义的,因为我检查了它上面的控制台日志,我回来了它是一个 li 项目。

最佳答案

问题是由于这一行:

$currentListItem = $currentListItem[index];

这里您通过索引访问一个 jQuery 对象,它返回一个 Element 对象,而不是一个 jQuery 对象。反过来,Elements 没有 children() 方法,因此会出现错误。

要解决此问题,请改为调用 eq() 以按索引获取 jQuery 集合中的元素:

$navButtons.on('click', navigationClick);

var $navButtons = $('nav a');
var $currentListItem = $('nav li')

function navigationClick() {
var index = $navButtons.index(this);
$currentListItem = $currentListItem.eq(index); // note .eq() here
$currentListItem.children('div').addClass("nav-selected");
}

关于javascript - 为什么我会收到未定义的 'children' 电话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669655/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com