Calling a jQuery function multiple times

↘锁芯ラ 提交于 2019-12-19 11:38:10

问题


So, I have this function in jQuery:

$(function(){ 
$( ".unfocused" ).click(function ClickHeader () {
    $( this ).addClass( "focused" );
    $( this ).removeClass( "unfocused" );
    $(".header").not(this).addClass( "unfocused" );
    $(".header").not(this).removeClass( "focused" );
});
});

It works perfectly when a header is clicked the first time, but when I try to click another unfocused header, the function doesn't work anymore. Is it because it runs on document .ready?
Thanks for your help!


回答1:


Change it like this:

  $( document ).on("click", ".unfocused", function() {
    $( this ).addClass( "focused" );
    $( this ).removeClass( "unfocused" );
    $(".header").not(this).addClass( "unfocused" );
    $(".header").not(this).removeClass( "focused" );
  });

This basically registers the event on the document. When you click a header, the event bubbles up to the document. There, the given selector is validated and the function is executed if needed.




回答2:


Here is a jsfiddle using the delegate operation for handling the event like you need.

http://jsfiddle.net/MN9Zt/2/

$("body").delegate(".unfocused", "click", function() {
    $(this).addClass("focused");
    $(this).removeClass("unfocused");
    $(".header").not(this).addClass("unfocused");
    $(".header").not(this).removeClass("focused");
});


来源:https://stackoverflow.com/questions/20035746/calling-a-jquery-function-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!