多次调用jQuery函数 [英] Calling a jQuery function multiple times
本文介绍了多次调用jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$(function(){
$(。 ).click(function ClickHeader(){
$(this).addClass(focused);
$(this).removeClass(unfocused);
$( ();
$(。header)。not(this).removeClass(focused);
});
});
第一次点击标题时,我尝试点击另一个不专心的标题,该功能不再起作用。是因为它运行在document.ready?
感谢您的帮助!
解决方案
这:
$(document).on(click,.unfocused,function(){
$(this).addClass(focused);
$(this).removeClass(unfocused);
$(。header)。not(this).addClass(unfocused );
$(。header)。not(this).removeClass(focused);
});
这基本上将事件记录在文档中。当您单击一个标题时,事件会冒泡到文档中。在那里,给定的选择器被验证,并在需要时执行函数。
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!
解决方案
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.
这篇关于多次调用jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文