为什么jQuery单击事件处理程序对于动态加载的DOM元素不能正常工作? [英] Why is jQuery on-click event handler not working properly for dynamic loaded DOM elements?

查看:93
本文介绍了为什么jQuery单击事件处理程序对于动态加载的DOM元素不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将JavaScript文件加载到主页中,然后导航到需要onclick函数的页面. onclick附加到通过AJAX调用随时间动态加载的内容上.我尝试达到的元素的构造如下:

I load my JavaScript file in the at my home page, then I navigate to the page where I need a onclick function. The onclick is attached to content that has been loaded dynamically over time via AJAX calls. The elements I try to reach are constructed like:

<a href="#" id="query_2" class="list-group-item query">Alle huurdergegevens</a>

在我的JavaScript文件中,我这样写:

And in my JavaScript file I wrote this:

$(".query").click(function() {
    var id = $(this).attr('id');
    id = id.replace(/\D/g,'');
    console.log(id);
    exeSQL(id);
});

当我单击该元素时,实际上什么也没发生..在控制台中什么也没登录,也没有错误..无法弄清楚我在做什么错..

When I click the element, literally nothing happens.. Nothing logged in the console, no errors aswell.. Can't figure out what I'm doing wrong tbh..

推荐答案

在创建DOM之后在DOM中加载任何元素时,则必须使用on

when you load any element in DOM after DOM is created then you have to handle click event like this with using on

$(document).on("click",".query",function() {
    var id = $(this).attr('id');
    id = id.replace(/\D/g,'');
    console.log(id);
    exeSQL(id);
});

这篇关于为什么jQuery单击事件处理程序对于动态加载的DOM元素不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆