javascript 页面加载后创建的 DOM 元素不会触发 Jquery 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21239210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:27:21  来源:igfitidea点击:

Jquery Event Not Triggering for DOM Elements Created after page load

javascriptjqueryhtmldom

提问by Talon06

I have a page that trigger a calculate() function when a html5 number field is changed I have bound just about every event I can think of to it and it works for the originally loaded DOM elements.

我有一个页面,当 html5 数字字段发生更改时,它会触发一个 calculate() 函数我已经绑定了我能想到的几乎所有事件,并且它适用于最初加载的 DOM 元素。

However, if I add elements after the dom is loaded the change functions do not trigger.

但是,如果我在加载 dom 后添加元素,则不会触发更改功能。

I added a button that runs the calculate() function and when click it will run for the newly created elements as well as the original ones.

我添加了一个运行 calculate() 函数的按钮,当单击它时,它将为新创建的元素以及原始元素运行。

So I know the code works but the event isn't firing for the newly created dom elements.

所以我知道代码有效,但事件不会为新创建的 dom 元素触发。

Jquery Triggers

Jquery 触发器

            $('.score').change(function() {
                calculate();
            });
            $('.score').bind('keyup mouseup', function() {
                calculate();
            });
            $('.score').mousewheel(function() {
                calculate();
            });
            $('.score').click(function() {
                calculate();
            });
            $('.score').keypress(function() {
                calculate();
            });

Calculate Function

计算函数

function calculate() {
            $("tbody tr").each(function() {
                row_total = 0;
                $(".score", this).each(function() {
                    row_total += Number($(this).val());
                });
                $(".total", this).val(row_total);
            });
            var arr = [];
            var row = 0;
            $("tbody tr").each(function() {
                $(".total", this).each(function() {
                    arr[row] = $(this).val();
                    row += 1;
                });
            });
            var sorted = arr.slice().sort(function(a, b) {
                return b - a
            })
            var ranks = arr.slice().map(function(v) {
                return sorted.indexOf(v) + 1
            });
            row = 0;
            $("tbody tr").each(function() {
                $(".place", this).each(function() {
                    $(this).val(ranks[row]);
                    row += 1;
                });
            });
            $("tbody tr").each(function() {
                $(".place", this).each(function() {
                    var p = $(this).val();
                    switch (p) {
                        case '1':
                            $(this).css('background-color', 'gold');
                            break;
                        case '2':
                            $(this).css('background-color', 'silver');
                            break;
                        case '3':
                            $(this).css('background-color', '#8c7853');
                            break;
                        case '4':
                            $(this).css('background-color', 'white');
                            break;
                        default:
                            $(this).css('background-color', 'white');
                    }
                });
            });
        }

genRow Function

genRow 函数

function genRow(i)
        {
            var x = "";
            for (var j = 0; j < i; j++) {
                x += '<tr class="competitors">';
                x += '<td class="row">';
                x += '<input class="name" type="text" />';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="score" type="number" step="1" min="-100" max="100" value="0" />';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="score" type="number" step="1" min="-100" max="100" value="0" />';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="score" type="number" step="1" min="-100" max="100" value="0" />';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="score" type="number" step="1" min="-100" max="100" value="0" />';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="score" type="number" step="1" min="-100" max="100" value="0" />';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="total" type="text" value="0"/>';
                x += '</td>';
                x += '<td class="row">';
                x += '<input class="place" type="text" value="0"/>';
                x += '</td>';
                x += '</tr>';
            }
            return x;
        }

HTML Code

HTML代码

<body>
    <table id="main">
        <tr>
            <td class="header">
                Name
            </td>
            <td class="header judge">
                Judge 1
            </td>
            <td class="header judge">
                Judge 2
            </td>
            <td class="header judge">
                Judge 3
            </td>
            <td class="header judge">
                Judge 4
            </td>
            <td class="header judge">
                Judge 5
            </td>
            <td class="header btn">
                <input id="btn_Total" type="button" value="Total"/>
            </td>
            <td class="header h_place">
                Place
            </td>
        </tr>
        <tr class="competitors">

        </tr>
        <tr>
            <td colspan="7"></td>
            <td class="header btn">
                <input id="btn_AddRow" type="button" value="Add Row"/>
            </td>
        </tr>
    </table>
</body>

回答by Satpal

Currently what you are using is called a directbinding which will only attach to element that exist on the page at the time your code makes the event binding call.

目前您使用的是直接绑定,它只会附加到您的代码进行事件绑定调用时页面上存在的元素。

You need to use Event Delegationusing .on()delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

在动态生成元素或操作选择器(如删除和添加类)时,您需要使用.on()委托事件方法使用事件委托。

i.e.

IE

$(document).on('event','selector',callback_function)

Example

例子

$(document).on('click', '.score', function(){
    //Your code
    alert("clicked me"); 
});

In place of documentyou should use closest static container.

代替document您应该使用最近的静态容器。

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件。通过选择一个在附加委托事件处理程序时保证存在的元素,我们可以使用委托事件将点击事件绑定到动态创建的元素,并避免频繁附加和删除事件处理程序的需要。