将事件选择器委托为第 n 个元素不起作用

delegate event selector as nth element not working

本文关键字:元素 不起作用 事件 选择器      更新时间:2023-09-26

我想为动态加载 Div 标签的按钮附加点击事件。我正在尝试在父 Dev 标签上使用委托事件。点击时应附加到第 n 个(假设 6 个)子div 标签。

$(".navigation-bar").delegate('.navigation-bar > :nth-child(6)',"click",function() {
..
})

上面的代码不是将事件附加到子级div。但是当我在整个页面加载后从控制台运行此代码时,它可以工作。

如果您的代码在加载后在控制台中工作,那么您的脚本很可能在 DOM 完成加载之前正在运行。首先通过记录运行代码的正上方的元素来测试是否是这种情况:

console.log( $(".navigation-bar")[0] ); //this could likely be undefined
console.log( $('.navigation-bar > :nth-child(6)')[0] ); //and this is likely undefined

如果它们未定义,请确保脚本在 body 元素的末尾运行,或者更好的是,在 jquery 的 ready 函数中运行所有代码:http://learn.jquery.com/using-jquery-core/document-ready/