单击时的JS选择器不适用于Django模型生成的内容 [英] JS selector on click not working for django model generated content

查看:98
本文介绍了单击时的JS选择器不适用于Django模型生成的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的错误,但是我有以下代码:

This might be a dumb mistake but I have this code:

$('#delete-btn').on('click', function(){
    return confirm('Are you sure you want to delete this?');
});

警报不会发生,但是使用此代码会发生:

the alert does not occur but with this code it does:

$(document).on('click', '#delete-btn', function(){
    return confirm('Are you sure you want to delete this?');
});

根据我的理解,

是同一件事,但是第二个尝试在每次单击指定ID的页面上进行处理.我尝试将其放在文档就绪块中,但这无济于事.

from what I understand they are the same thing, but the second tries to process the event every click on the page looking for the specified id. I tried putting it in a document ready block but that didn't help.

我不明白为什么一个有效,而另一个无效.

I don't understand why one works and the other does not.

推荐答案

如果您引用的元素当时是文档的一部分,那么您的第一个代码也将起作用,因此请确保将脚本靠近文档末尾,或者将其包装在ready处理程序中:

Your first code will also work if the element you reference is part of the document at that time, so make sure to put the script near the end of the document, or else wrap it in the ready handler:

$(function () {
    $('#delete-btn').on('click', function(){
        return confirm('Are you sure you want to delete this?');
    });
});

第二个脚本($(document).on('click' ...))有效,因为文档从一开始就存在,因此将处理程序绑定到该脚本.单击时,事件会冒泡到达文档,并且处理程序将启动.

The second script ($(document).on('click' ...)) works, because the document is there from the start, so the handler is bound to it. At the time of the click, the event bubbles up to the document and the handler kicks in.

如果页面加载时您的按钮不在文档中,而是动态生成的,则上述代码可能仍会很快找到按钮 .您提到django生成按钮.当文档准备就绪时,它可能还会捕获一个事件,然后查询数据库,等待其答复(在大多数情况下,这是异步的),然后才添加按钮.如果到那时您的代码已经运行,则它错过了该按钮,并且没有在该按钮上附加事件处理程序.

If your button is not in the document when the page loads, but is generated dynamically, the above code might still look for the button to soon. You mentioned django generates the button. It probably also captures an event when the document is ready, then queries the database, waits for its reply (in most cases this is asynchronous), and only then adds the button. If your code has already run by that time, it missed the button, and did not attach an event handler to it.

在那种情况下,使用事件委托到文档级别($(document).on('click' ...))确实是一个更可靠的解决方案.

In that case, it is indeed a more solid solution to use the event delegation to the document level ($(document).on('click' ...)).

这篇关于单击时的JS选择器不适用于Django模型生成的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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