在jQuery和changeclass上使用('click')事件只触发一次
问题描述:
在下面的脚本中,第一次点击“toggleExtras”跨度。但随后的点击无效。我试图使用on('click')方法和toggleClass来为切换和非切换状态定义事件。在jQuery和changeclass上使用('click')事件只触发一次
jQuery(document).ready(function()
{
jQuery('.toggleExtras').on('click', function(e)
{
//jQuery('.extras').slideToggle(); //This works but bounces twice.
jQuery('.extras').show();
jQuery('.toggleExtras').text('Hide Advanced Options');
jQuery('.toggleExtras').toggleClass('toggleExtras toggleExtrasHide');
});
jQuery('.toggleExtrasHide').on('click', function(e)
{
jQuery('.extras').hide();
jQuery('.toggleExtrasHide').text('Show Advanced Options');
jQuery('.toggleExtrasHide').toggleClass('toggleExtrasHide toggleExtras');
});
});
HTML:
<span class="toggleExtras">Show Advanced Options</span>
答
这是因为.toggleExtrasHide
不会在初始化时存在...
我重新写你这样的代码:
jQuery('.toggleExtras').on('click', function(e){
jQuery('.extras').toggle();
jQuery(this).text(function(el, currentValue){
return currentValue == "Show Advanced Options" ? "Hide Advanced Options" : "Show Advanced Options";
});
});
了解更多关于.toggle()
:http://api.jquery.com/toggle/
了解更多关于.text()
:http://api.jquery.com/text/
+0
+1。完美的作品。谢谢您的帮助! – RegEdit 2013-02-26 04:10:24
你能张贴上的jsfiddle错误的例子吗? – 2013-02-26 03:48:16
我没有收到控制台错误。对已更改的类元素的点击无效。该类被改变,但on('click')不会为该元素触发。 – RegEdit 2013-02-26 03:49:16