简体   繁体   English

使用 jQuery .on() 方法不会在动态创建的元素上绑定事件

[英]Using jQuery .on() method doesn't bind event on dynamically created element

I am currently working on a website that has a logout button which gets dynamically inserted into a sidebar whenever the window reaches a certain size.我目前正在开发一个网站,该网站有一个注销按钮,每当窗口达到一定大小时,该按钮就会动态插入到侧边栏中。 When I click on the log out button I want to call the method logOut();当我点击注销按钮时,我想调用方法logOut();

I looked over these other posts and the solutions don't seem to be working for me.我查看了这些其他帖子,这些解决方案似乎对我不起作用。 The method gets called if I click on the element while it's on the main page, but when I resize the window and the element gets "re-added" to the webpage it doesn't do anything (The ID selector is the right one because the style is all there).如果我在主页面上单击元素,则会调用该方法,但是当我调整窗口大小并且元素被“重新添加”到网页时,它不会执行任何操作(ID 选择器是正确的,因为风格就在那里)。

$(document).ready(function()
{
    $(document).on("click", "#btnLogOut", function()
    {
        logOut();
    });
});

I expected the logOut() method to be called after clicking on the anchor tag, but it doesn't do anything even if the .on() method is supossed to take care of dynamically created elements我希望在单击锚标记后调用logOut()方法,但即使.on()方法被认为处理动态创建的元素,它也不会执行任何操作

EDIT: This is how I re-add the element to the page after resizing.编辑:这就是我在调整大小后将元素重新添加到页面的方式。 The nav element that includes the logout anchor tag is made into a list by a navList();包含注销锚标记的 nav 元素由navList();制成列表navList(); method and then gets appended to the body.方法,然后附加到主体。 I made sure to specify that the logout button needs to keep its ID.我确保指定注销按钮需要保留其 ID。 Only going to add the code relevant to the log out button.只打算添加与注销按钮相关的代码。

$.fn.navList = function() {

    var $this = $(this);
        $a = $this.find('a'),
        b = [];

    $a.each(function() {

        var $this = $(this),
            indent = Math.max(0, $this.parents('li').length - 1),
            href = $this.attr('href'),
            target = $this.attr('target');
        if($a.attr("id") === "btnLogOut") {
            console.log($a);
            b.push(
                '<a ' +
                    'id="btnLogOut" ' + 
                    'class="link depth-' + indent + '"' +
                    ( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
                    ( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
                '>' +
                    $this.text() +
                '</a>'
            );
        }

    });

    return b.join('');

};
            $(
                '<div id="navPanel">' +
                    '<nav>' +
                        $('#btns').navList() +
                    '</nav>' +
                '</div>'
            )
                .appendTo($body)

Let not your heart be troubled, jQuery .on() absolutely works with a dynamically-injected element.别担心, jQuery .on()绝对适用于动态注入的元素。 So, what could be causing it to not work in this instance?那么,什么可能导致它在这种情况下不起作用?

First, most common, cause: spelling and/or capitalization.首先,最常见的原因:拼写和/或大写。 Did you not capitalize one of the characters?您没有将其中一个字符大写吗? For eg #btnLogOut is not the same as #btnLogout例如, #btnLogOut#btnLogout

Second, equally common error: duplicate IDs on the page.其次,同样常见的错误:页面上的 ID 重复。 Change the ID for the button you want and test again (add the three-character suffix _zq to the end of the ID - a suitably unlikely string suffix - and remember to change both the HTML ID and the ID referenced by jQuery) .更改所需按钮的 ID 并再次测试(在 ID 末尾添加三个字符的后缀_zq - 一个不太可能的字符串后缀 - 并记住更改 HTML ID 和 jQuery 引用的 ID)

Sometimes, you just need to be more specific.有时,您只需要更具体。 Instead of #btnLogOut , try adding some parent IDs and classes.尝试添加一些父 ID 和类,而不是#btnLogOut If, for example, this was your structure:例如,如果这是您的结构:

<div class="row bob">
    <div class="container sam ed tom">
        <div class="dialog frank lg pc6">
            <div class="dlg-bottom">
                <button id="btnLogOut">Log Out</button>

then make your jQuery statement:然后让你的 jQuery 语句:

$(document).on('click', '.row .container .dialog .dig-bottom #btnLogOut', function(){
    //code goes here
});

How to test what you have:如何测试你所拥有的:

At the point where the button has been been added to the page and is visible on screen:在按钮已添加到页面并在屏幕上可见时:

  1. Right-Click on the button, choose Inspect Element from the pop-up menu右键单击按钮,从弹出菜单中选择Inspect Element

  2. Chrome's DevTools will open Chrome 的 DevTools 将打开

  3. If the console is not visible as the bottom half of the DevTools window, press Esc如果控制台在 DevTools 窗口的下半部分不可见,请按Esc

  4. In the console input area, type: $('#btnLogOut').length在控制台输入区,输入: $('#btnLogOut').length

You should see the number 1 appear below that line.您应该会看到数字1出现在该行下方。

If you get the message Uncaught TypeError: $ is not a function , then you should first inject jQuery into DevTools and try step 4 again.如果您收到消息Uncaught TypeError: $ is not a function ,那么您应该首先将 jQuery 注入 DevTools并再次尝试步骤 4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM