开发者

jquery click event

开发者 https://www.devze.com 2023-01-15 05:30 出处:网络
I have some jquery that looks like this, $(\'.career_select .selectitems\').click(function(){ var selectedCareer = $(this).attr(\'title\');

I have some jquery that looks like this,

    $('.career_select .selectitems').click(function(){
    var selectedCareer = $(this).attr('title');
    $.ajax({
       开发者_如何转开发 type: 'POST',
        url: '/roadmap/step_two',
        data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
        success: function(html){
            $('.hfeed').append(html);
            $('#grade_choice').SelectCustomizer();
          }
    });
});

My problem is that if the user keeps clicking then the .hfeed keeps getting data appended to it. How can I limit it so that it can only be clicked once?


Use the one function:

Attach a handler to an event for the elements. The handler is executed at most once per element

If you wanted the element to only be clicked once and then be re-enabled once the request finishes, you could:

A) Keep a state variable that updates if a request is currently in progress and exits at the top of the event if it is.
B) Use one, put your code inside a function, and rebind upon completion of request.

The second option would look like this:

function myClickEvent() {
    var selectedCareer = $(this).attr('title');
    var that = this;

    $.ajax({
        type: 'POST',
        url: '/roadmap/step_two',
        data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
        success: function(html){
            $('.hfeed').append(html);
            $('#grade_choice').SelectCustomizer();
        },
        complete: function() {
            $(that).one('click', myClickEvent);
        }
    });
}

$('.career_select .selectitems').one('click', myClickEvent);


You can either use a global variable like

var added = false;
$('.career_select .selectitems').click(function(){
    if(!added) {
        // previous code here
        added = true;
    }
});

or use .one("click", function () { ... }) instead of the previous click function to execute the handler at most once per element. See http://api.jquery.com/one/ for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消