简体   繁体   English

使用jQuery .on()方法不适用于动态创建的元素

[英]Using jQuery .on() method doesn't work 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();

The ID of the anchor tag is "btnLogOut" everywhere(even checked it by searching in my IDE in case there are any invisible characters or something). 锚标签的ID到处都是“btnLogOut”(甚至通过在我的IDE中搜索来检查它,以防有任何不可见的字符或其他东西)。

There is always only one log out anchor tag on every page. 每页上始终只有一个注销锚标记。 To be sure, I replaced "btnLogOut" with "btnLogOut_zq" everywhere and the error persisted. 可以肯定的是,我用“btnLogOut_zq”替换了“btnLogOut”,并且错误仍然存​​在。

I used setInterval(function(){ console.log($("#btnLogOut").length); },1); 我使用了setInterval(function(){ console.log($("#btnLogOut").length); },1); and this returns 1 constantly while resizing the window and making it bigger and then smaller and so on so the element is always present on the page. 并且这会在调整窗口大小并使其变大然后变小等时不断返回1,因此元素始终存在于页面上。

Using .on() method to detect a click and then call logOut(); 使用.on()方法检测单击然后调用logOut(); method 方法

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

This is what I use to take the original anchor tag and put it in the sidebar(Only the part that's relevant to the logout 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>'
)

Creating elements by string does not "instantiate" them inside of the DOM . 按字符串创建元素不会在DOM内“实例化”它们。 To get around this you would have to create the elements by means of the DOM's Javascript API (or serverside rendering of elements before the DOM loads, EG: an HTML file). 要解决这个问题,你必须通过DOM的Javascript API(或DOM加载前的服务器端元素呈现,EG:HTML文件)来创建元素。

Although there are a few ways to do it, this is a good example with jQuery: 虽然有几种方法可以做到这一点,但这是jQuery的一个很好的例子:

b.push(
    $('<a />', {id:"btnLogout", class: "link depth-1", target:"_BLANK", "href":"HTTP://", "text":$this.text()})
);

Assuming b is an existing array that'll be appended to another element or iterated over. 假设b是一个现有的数组,它将被附加到另一个元素或迭代。

Learn more about creating elements the "correct" way on the Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement 了解有关在Mozilla文档上以“正确”方式创建元素的更多信息: https//developer.mozilla.org/en-US/docs/Web/API/Document/createElement

EDIT: 编辑:

For your nesting further down: 为了进一步向下筑巢:

$('<div />', {id: 'navPanel'}).append(
    $('<nav />', html: $("#btns").navList())
);

If you have access to ES6 then you can use Template Literals for this: 如果您有权访问ES6,那么您可以使用模板文字:

$(
    `<div id="navPanel">
        <nav>
            $($('#btns').navList())
        </nav>'
    </div>`
)

I'm not sure if the syntax will conflict with the jQuery shorthand dollar sign. 我不确定语法是否会与jQuery简写美元符号冲突。

Just put: 刚刚放:

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

Outside the $(document).ready $(document).ready

Careful, because by looking at your HTML page code, you have two times the ID #btnLogOut . 小心,因为通过查看您的HTML页面代码,您有两次ID #btnLogOut

EDIT 1: 编辑1:

Take a look at this JSFiddle that I created in order to show you that even elements created on the fly have the onclick event attached. 看看我创建的这个JSFiddle ,以便向您展示即使是动态创建的元素也附加了onclick事件。

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

相关问题 .focus()不适用于jQuery动态创建的元素 - .focus() doesn't work on element created by jQuery dynamically jQuery-在动态创建的元素上单击(使用“ .on()”)无效,只能双击。 为什么? - jQuery - click (with using “.on()”) on a dynamically created element doesn't work, only double-click. Why? jQuery不适用于创建后的元素 - JQuery doesn't work with the after created element jQuery click事件不适用于动态创建的表单字段 - jQuery click event doesn't work for dynamically created form field 使用 JavaScript createElement() 方法在 keydown 上创建的元素不适用于 jQuery draggable() 方法 - Element created on keydown using JavaScript createElement() method won't work with the jQuery draggable() method jQuery事件不适用于新创建的元素 - jQuery event doesn't work at new created element jQuery .load()在新创建的DOM div元素上不起作用 - jQuery .load() doesn't work on a newly created DOM div element jQuery UI Draggable在创建的元素上不起作用 - jQuery UI draggable doesn't work on created element Jquery 方法不适用于动态生成的元素 - Jquery method doesn't work on dynamically generated elements 动态创建的元素上的 addEventListener 不起作用 - addEventListener on dynamically created elements doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM