单击按钮,添加表单,向下滑动并在第二次单击时向上滑动
我试图让一个表单元素在该div中包含的按钮单击下滑动div。
再次单击该按钮时,我希望该窗体为slideUp();
所以我的HTML就像
我试过这个:
$( ".enquiry-button" ).click( function(e) { e.preventDefault(); e.stopPropagation(); $(this).closest( '.cell' ).append( "" + "" + "" ); $(this).closest( '.cell' ).find(".enquiry-form:last").slideDown("slow"); });
但是click函数会使用类查询按钮触发每个元素(正如您所期望的那样)。
有更简单的方法吗?
UPDATE
问题是我的
$(window).load
解决了这个问题。
你非常接近……你在这里错过的是,一旦你点击一个div,你就构建了一个表单元素。 单击之前元素长度将为0,单击后长度将开始增加。 基于此,您可以toggle the slider
。
JS:
$( ".enquiry-button" ).click( function(e) { e.preventDefault(); e.stopPropagation(); alert("length::"+$(this).parents('.cell').find('form').length); if($(this).parents('.cell').find('form').length==0){ $(this).closest( '.cell' ).append( "" + "" + ""); $(this).closest( '.cell' ).find(".enquiry-form:last").slideDown("slow"); }else{ $(this).closest( '.cell' ).find(".enquiry-form:last").slideToggle("fast"); } });
在这里找到小提琴: http : //jsfiddle.net/JPUTy/5/
您可以看到我在此处有一个提醒,它会在每次点击后显示表单的长度,这样您就可以更轻松地了解后台发生的情况。
可能你不添加另一个,但在第三次点击时切换幻灯片? 需要隐藏新表单以允许slideDown
,缓存单元格选择器以供重用。
$(".enquiry-button").click(function (e) { e.preventDefault(); e.stopPropagation(); var cell = $(this).closest('.cell'); if (cell.find('.enquiry-form').length) { cell.find('.enquiry-form').slideToggle(); } else { cell.append( "" + "" + ""); cell.find('.enquiry-form').hide().slideDown("slow"); } });
实际样本: http : //jsfiddle.net/GMjNS/
注意每个延迟评论,如果您使用动态元素,请将第一行更改为:
$(document).on("click", ".enquiry-button", function (e) {
如果你有0个元素,它将没有可点击的项目,所以应该没问题。 请注意,您应该注释绑定到文档,而是使用更接近的包装器(如div包装器等)绑定到:example
$('#mywrapperelementid').on("click", ".enquiry-button", function (e) {
检查点击元素的父元素是否具有表单子元素,如果有,则使用slideToggle()
!
现场演示
的JavaScript / JQuery的
$(".enquiry-button").click(function (e) { e.preventDefault(); e.stopPropagation(); if (!$(this).parents('.cell').find('form').length) { $(this).closest('.cell').append( "" + "" + ""); $(this).closest('.cell').find(".enquiry-form:last").slideDown("slow"); } else $(this).closest('.cell').find(".enquiry-form:last").slideToggle("slow"); });
CSS
.enquiry-form { display:none; }
您可以在第一次单击后向.cell
添加一些类,并在第二次单击后删除类:
$(".enquiry-button").click(function (e) { var $this = $(this), $parent = $this.parent(); if (!$parent.hasClass('opened')) { if (!$parent.find('form').length) { $parent.append(''); } $parent.addClass('opened'); } else { $parent.removeClass('opened'); } });
示例: http : //jsfiddle.net/uNwLn/
如果您只想在当时打开一个表单,这是一个工作示例 。
jQuery的:
$('.enquiry-button').click(function(e){ $('.cell .enquiry-form:visible').slideUp('slow', function(){ $(this).remove(); }); if( $(this).parent('.cell').hasClass('active') ) { $(this).parent('.cell').removeClass('active'); } else { $('.cell').removeClass('active'); $(this).parent('.cell').addClass('active'); $('.cell.active').append("" + "" + ""); $('.cell.active .enquiry-form').hide().slideDown('slow'); } });