对于页面加载时不存在的 类,我是否必须以不同方式处理点击事件?
Do I have to handle click events differently for classes that are not present when the page loads?
我的 jquery 中有一个点击事件,看起来像这样...
$(document).ready(function(){
//some other stuff
$('.tag_result').click(function(){
console.log("clicked");
});
});
我这辈子都做不到。我在 document.ready 函数中也有一些代码用 class tag_result
生成一些 div。在插入这些 div 后检查 html,我确认它们的放置和格式正确,包括它们的 class="tag_result" 标识符。
为了尝试解决这个问题,我将我的问题简化为一个 jsfiddle 程序,令我惊讶的是,它按预期工作了!我可以检测到的唯一区别是我在 .click() 函数中引用的 html 元素始终存在于 jsfiddle 应用程序中,而不总是存在于我的实际应用程序中。
这是导致我出现问题的原因吗?还是我的代码肯定有其他问题?
动态插入元素需要使用委托
$(document).ready(function(){
//some other stuff
$(document).on('click', '.tag_result', function(){
console.log("clicked");
});
});
我的 jquery 中有一个点击事件,看起来像这样...
$(document).ready(function(){
//some other stuff
$('.tag_result').click(function(){
console.log("clicked");
});
});
我这辈子都做不到。我在 document.ready 函数中也有一些代码用 class tag_result
生成一些 div。在插入这些 div 后检查 html,我确认它们的放置和格式正确,包括它们的 class="tag_result" 标识符。
为了尝试解决这个问题,我将我的问题简化为一个 jsfiddle 程序,令我惊讶的是,它按预期工作了!我可以检测到的唯一区别是我在 .click() 函数中引用的 html 元素始终存在于 jsfiddle 应用程序中,而不总是存在于我的实际应用程序中。
这是导致我出现问题的原因吗?还是我的代码肯定有其他问题?
动态插入元素需要使用委托
$(document).ready(function(){
//some other stuff
$(document).on('click', '.tag_result', function(){
console.log("clicked");
});
});