单击后on方法无效的click事件

时间:2013-08-07 04:12:17

标签: javascript jquery

它几乎没有工作,它第一次起作用,但不是下一次打击..

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

itemClick是我的自定义函数..

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

1 个答案:

答案 0 :(得分:2)

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

尝试委派活动。

替换

$('.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