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

标签 javascript jquery html dom

<分区>

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

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

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

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

Jquery 触发器

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

计算函数

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(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代码

<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>

最佳答案

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

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

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

例子

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

代替 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.

关于javascript - 页面加载后创建的 DOM 元素不触发 Jquery 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21239210/

相关文章:

Javascript 回调函数在 Firefox 中抛出错误 "Callback is not a function"

javascript - 如何在 .on "click"事件中获取按钮 ID

php - 通过 AJAX 发送特殊字符( "&lt"、 "&gt"、 "&amp")

jquery - 如何使用 jQuery UI selectMenu 小部件在下拉列表中创建 3 列?

html - 在链接鼠标悬停时显示播放图标

javascript - 如何使谷歌地点自动完成结果显示在输入上方

javascript - scroll spy 和 afix 的问题

未应用 JQuery themeroller 悬停

jQuery下拉菜单闪烁

jquery - DIV 中的可拖动叠加弹出窗口