0

I have one problem with my function in jQuery. First I will explain what I am trying to do.

I have two elements inside a div, the p element and input element. The element p is visible, and the input element stay hidden. When the user clicks in the p element, the input element will appear (show and focus) and the p element will disappear (hide). When the input field appears, if the user types something and presses enter, a new li element will be added.

This is my current code:

function createFolder() {
    // Should be a clickable element
    $('#create p').click(function() {

        // Hide the p element
        $(this).hide();

        // Show and focus the createFolder (input field)
        $('#createFolder').show().focus();

        // If press a key inside input field
        $('#createFolder').keypress(function(event) {
            // If this key is "enter"
            if (event.keyCode == 13) {
                // Add a new li element inside menu
                $('#menu').append('<li class="expandable"><a href="#">' + $('#createFolder').val() + '</a></li>');
            }
        });

        // Focus out the input field
        $('#createFolder').focusout(function() {
            // Hide the input field element
            $(this).hide();
        });
    });
}

http://i.imgur.com/HZoDr.png

But I have a problem, when I click in p element or focus out (3 clicks for example), when I type something and press enter, three li elements are added to my menu. It's like a loop, it counts my clicks and focus out and when I type something, it adds that number of elements. Someone can help me with this? And if is possible, teach me why this happens?

4

3 回答 3

0

尝试这个

var items = $('#menu').parent().children(".expandable").length;
if(items > 0){
//skip doing what you are doing.
}else{
$('#menu').append('<li class="expandable"><a href="#">' +  $('#createFolder').val() + '</a></li>');
}
于 2012-09-11T12:27:02.293 回答
0

当您调用此代码时:

$('#createFolder').keypress(function(event) {
    // If this key is "enter"
    if (event.keyCode == 13) {
        // Add a new li element inside menu
        $('#menu').append('<li class="expandable"><a href="#">' + $('#createFolder').val() + '</a></li>');
    }
});

您正在keypress为该元素添加一个新的事件处理程序。重要的一点是添加,jQuery 不会覆盖现有的事件处理程序 - 每次调用那段代码时,都会向元素添加一个新的事件处理程序。

而且,由于该代码位于元素的click事件处理程序中<p>,因此每次单击该元素时,您都会获得该keypress事件的附加处理程序。如果单击 3 次,您将拥有三个事件处理程序,每个事件处理程序都会在您按下某个键时触发。

最简单的解决方案是简单地移动该代码以将事件处理程序绑定到元素的事件keypress处理程序之外。click<p>

于 2012-09-11T12:35:51.280 回答
0
 $('#menu').html('<li class="expandable"><a href="#">' +  $('#createFolder').val() + '</a></li>');
于 2012-09-11T12:29:06.907 回答