[英]Calling a jQuery function multiple times
So, I have this function in jQuery: 所以,我在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?
是因为它在文件.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.
在那里,验证给定的选择器并在需要时执行该功能。
Here is a jsfiddle using the delegate operation for handling the event like you need. 这是一个jsfiddle使用委托操作来处理您需要的事件。
http://jsfiddle.net/MN9Zt/2/ 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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.