简体   繁体   中英

How can I make sure that my click function executes one time only with Jquery?

I have jquery code that runs everytime everytime I click on my button but I only want it do do the stuff inside the click function once.. Beacuse otherwise my jquery code will duplicate values in my tbody td.

Here is my jquery code:

  $(function () {
        $('#next-step').click(function () {
            $('#S').append($('#SubjectTypeName option:selected').text());
            $('#T').append($('#TeamName option:selected').text());
            $('#C').append($('#ConsultantName option:selected').text());
            $('#K').append($('#company option:selected').text());
            $('#KP').append($('#ContactPerson').val());
            $('#P').append($('#date').val());
        });

    });

And here is the jsfiddle: http://jsfiddle.net/82U2W/

Any help is appreciated.

Thanks in advance!

I am not sure if I understood correctly, try .one if you want to execute the handler only once

$(function() {
    $('#next-step').one('click', function() {
        $('#S').append($('#1 option:selected').text());
        $('#C').append($('#2').val());
        $('#T').append($('#3').val());
    });
});

DEMO

Or perhaps you want the value to be copied over instead of appending then try like below,

$(function() {
    var copiedText = 'Copied Value: ';
    $('#next-step').on('click', function() {
        $('#S').text(copiedText + $('#1 option:selected').text());
        $('#C').text(copiedText +$('#2').val());
        $('#T').text(copiedText +$('#3').val());
    });
});

DEMO

I would say the easiest way is to use jQuery.one :

 $(function () {
        $('#next-step').one('click', function () {
            $('#S').append($('#SubjectTypeName option:selected').text());
            $('#T').append($('#TeamName option:selected').text());
            $('#C').append($('#ConsultantName option:selected').text());
            $('#K').append($('#company option:selected').text());
            $('#KP').append($('#ContactPerson').val());
            $('#P').append($('#date').val());
        });

    });

use a variable that would control the button when clicked.

$(function () {
    $('#next-step').click(function () {
        if(cmdCtrl){
           $('#S').append($('#SubjectTypeName option:selected').text());
           $('#T').append($('#TeamName option:selected').text());
           $('#C').append($('#ConsultantName option:selected').text());
           $('#K').append($('#company option:selected').text());
           $('#KP').append($('#ContactPerson').val());
           $('#P').append($('#date').val());
        cmdCtrl=false;
        }
    });

});

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