Jquery wrapInner - 排除第一个元素

问题描述 投票:4回答:4

我试图使用图例标记上的click事件打开/折叠我的网站的部分字段集。但是我需要使用wrapInner在fieldset中添加一个div来隐藏内容......但是这也隐藏了传说(我肯定不想这样做):-)。我如何使用wrapInner但指定不隐藏图例(或者是字段集中包含的第一个元素 - 因为它始终是图例)。

$("#mainarea fieldset").wrapInner("<div class='fieldsetWrapper'></div>");

$("#mainarea fieldset:not(:first)").addClass("fsClosed"); // Close all fieldsets within the main area (but not the first one)

$("#mainarea fieldset legend").mousedown(function(){  // When clicking the legend of a fieldset ...
    $("#mainarea fieldset:not(.fsClosed)").addClass("fsClosed");  // If it's already open, close it
    $(this).parent().removeClass("fsClosed");  // If it's closed, remove the closed class from the containing fieldset
    return false;
}); 

干杯马克

jquery wrapper
4个回答
7
投票

为了回应你在Pim的例子中的评论,你需要遍历字段集

$('#mainarea fieldset').each(function(){
   $(this).children().not('legend').wrapAll("<div class='fieldsetWrapper'></div>");
});

你可能可能会重构这样的事情;

$('#mainarea fieldset').each(function(){
   $(':not(legend)', this).wrapAll("<div class='fieldsetWrapper'></div>");
});

4
投票
$('#mainarea fieldset').children(':gt(0)').wrapAll("<div class='fieldsetWrapper'></div>");

这应该可以解决问题。 有关wrapAll函数的信息:http://docs.jquery.com/Manipulation/wrapAll#html>

编辑 可能更好:

$('#mainarea fieldset').children().not('legend').wrapAll("<div class='fieldsetWrapper'></div>");

1
投票

我最终使用以下解决方案:

//Wrap everyting in the fieldset tags
$('#mainarea fieldset').wrapInner("<div class='fieldsetWrapper'></div>");
 
//for each legend tag move it out of the newly created wrapping div 
$('legend').each(function(){
  $(this).insertBefore($(this).parent());
});

首先,它将所有内容包装在fieldset标记内(包括图例),然后它“展开”图例标记。


0
投票
$(document).ready(function(){
    $("fieldset legend").click(function(){
        $(this).parent().children().not('legend').toggle("slow");
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.