简体   繁体   中英

Jquery on click strange behavior when generating list elements

I will post the code first and then try to go into details about my issue.

            projNav.on('click', '#editProj', function(event) {
            event.preventDefault();
            clearContent(returned);
            clearContent(projEditor);

            var editMain = $('#editMain'),
                editNav = $('#editNav'),
                layerCount = 1;

            // Add new layer button
            projEditor.html('<div id="editNav"><ul id="layers"><li id="new_layer">+</li></ul></div><div id="editMain"></div>');
            // Add new layer button functionality
            projEditor.on('click', '#new_layer', function(event) {
                event.preventDefault();
                $('#layers').append('<li id="layer" name="layer'+layerCount+'">'+layerCount+'</li>');
                layerCount++;
            });

            // Clicking on layer functionality
            projEditor.on('click', '#layer', function(event) {
                event.preventDefault();
                var name = $(this).attr('name');
                console.log(name);
            });             
        });

So basically what we have here is a button (#editproj) which when clicked it will generate another button (#new_layer) that allows the user to create one list element in the 'ul' that this last button is also a part of.

This works fine if you press the #editProj button only once, however if you click on it twice and then click the #new_layer button you will get the 'li' element added twice. So how many times you click the #editProj button, that many times the 'li' element gets inserted.

I`d like to understand this behavior but I can't seem to find something similar posted anywhere, so if anyone could steer me in the right direction i'd very much appreciate it.

Cheers!

you need to set the on to off before setting it to on again.

Make it

 projEditor.off('click', '#new_layer' ); //this line is required to set on to off
 projEditor.on('click', '#new_layer', function(event) {
                event.preventDefault();
                $('#layers').append('<li id="layer" name="layer'+layerCount+'">'+layerCount+'</li>');
                layerCount++;
            });
projNav.one('click', '#editProj', function(event) {

Try this code. It allows one click and prevent the processing of codes for double click and multiple clicks. Refer the below link How to prevent a double-click using jQuery? to get more idea. I think it will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM