在单击导航中的一个按钮后,我尝试将一个类附加到 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/