javascript - 我的点击事件与 on 方法在点击后不起作用

标签 javascript jquery

它几乎不起作用,第一次起作用,但下一次就不起作用了..

$('.edit').on('click', itemClick);

itemClick 是我的自定义函数..

http://jsfiddle.net/nurullia/ndCty/1/

最佳答案

您似乎正在向页面动态添加元素。

尝试委派事件。

替换

$('.edit').on('click', itemClick);

$(document).on('click', '.edit', itemClick);

代码

$(document).ready(function () {
    // Event when clicked on li
    $(document).on('click', 'li', function () {
        $('li').removeClass('active');
        $(this).addClass('active');
    });

    // Delegate the .edit event
    $(document).on('click', '.edit', itemClick);
    // Delegate the input event
    $(document).on('blur', 'input', editInputBlur);

    function itemClick(e) {
        // Stop the propagation when you click on edit
        e.stopPropagation();
        var $this = $(this),
            // Find the closest li
            $li = $this.closest('li'),
            // Get the text
            txt = $li.find('.items').text();
        // Add and remove class for li
        $li.addClass('active').siblings().removeClass('active');
        // Empty the li
        $li.empty();
        // Create input and append it to $li
        var $input = $("<input type='text' maxlength='30'/>").val(txt);

        $input.appendTo($li).focus();
    }


    function editInputBlur(e) {
        // You can use $(this) here directly as that is the event target
        var $this = $(this),
            v = $this.val(); // new edited value

        if (v.trim() !== "") {
            var html = '';
            html += "<a href='#'><span class='items'>" + v + "</span></a>";
            html += "<a href='#'><span class='edit'>edit</span></a>";
            var $a = $(html);
            // Use closest so that it does not break if any
            // extra container is added later
            $this.closest('li').append($a);
            $this.remove();
        }
    }

});

<强> Check Fiddle

关于javascript - 我的点击事件与 on 方法在点击后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094538/

相关文章:

javascript - 有没有办法跟踪对 HTML 元素的所有更改?

javascript - 从包含对象的数组中找到最小值的最佳方法

Javascript合并具有相同对象名称的嵌套数组?

Javascript 类似 oop 的失败(?!?)

javascript - 顺利直接移动到另一个div(过渡)

javascript - 使用相同的 CSS 样式创建多个复选框

javascript - 右动画jquery

javascript - jQuery.parseJSON 与 JSON.parse

javascript - 预览时 jQuery 似乎不起作用

php - 如何在每天午夜 12 点旋转图像?