0

它几乎没有工作,它第一次工作,但没有下一次命中..

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

itemClick 是我的自定义函数..

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

4

1 回答 1

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();
        }
    }

});

检查小提琴

于 2013-08-07T04:18:55.430 回答