0

我在一个我无法控制的框架之上进行编码,因此需要解决所生成内容的限制。

我正在尝试做一个 jquery UI 手风琴,但需要手风琴包含标题后面的两个元素,而不仅仅是一个。

例如,被吐出的代码是(删除了中间的一堆):

<h2>HEADER</h2>
<div>ITEM DESCRIPTION</div> 
<fieldset>
    <legend>Prices</legend>
    <div class="prices">
        <div class="productline" ><label>Price:</label>
                    <div  class="amount">$97.50</div></div>

    </div>
</fieldset>

这一切都需要进入单个手风琴项,但此时手风琴使用h2作为标题,带有描述的div作为手风琴内容,然后将后面的字段集留在手风琴之外。由于我无法控制生成的代码将它们都包装在一个 div 中,有没有办法告诉手风琴使用标题后面的两个项目,而不是一个?

我正在使用的 jquery 是:

$(function() {
    $( ".productindex" ).accordion({
        active: false,
        collapsible: true,
        autoHeight: true,
        header: 'li>form>h2'
    });
});

更复杂的是,有些项目没有描述,所以如果任何脚本可以在字段集可能不存在之前容纳初始 div,那就太好了 - 但最坏的情况是我可以确保每个项目都有描述。

谢谢你的帮助!

4

1 回答 1

2

根据我最初的评论,您可以获取需要成为“手风琴内容”的所有内容并将其全部包装在适当的元素中,以便手风琴功能起作用。

需要了解 HTML 的周围结构才能确定用于抓取这些元素的最佳选择器。让我们想象一下,您的结构有点类似于 jQuery UI 网站上的演示,除了使用不可更改的标记而不是 div:

<h2>HEADER</h2>
<div>ITEM DESCRIPTION</div> 
<fieldset>
    <legend>Prices</legend>
    <div class="prices">
        <div class="productline" >
            <label>Price:</label>
               <div  class="amount">$97.50</div>
        </div>
    </div>
</fieldset>

<h2>HEADER</h2>
// whoops, no description!
<fieldset>
    <legend>Prices</legend>
    <div class="prices">
        <div class="productline" >
            <label>Price:</label>
               <div  class="amount">$105.50</div>
        </div>
    </div>
</fieldset>

我们可以使用h2节点作为选择的入口点。您真正想要做的是选择所有可用的直到下一个(当DOM 树的那个分支中h2没有更多内容时它也会结束)。h2由于这种选择的本质,您是否有项目描述或其他元素并不重要。然后我们在所有找到的元素周围添加一个新的包装器。

我不知道这是否是最完善的代码(人们通常不喜欢使用.each(),但我发现它在这里很方便),但这是我想出的:

var headers = $('h2');
headers.each( function() {
  var toWrap = $(this).nextUntil('h2');
  toWrap.wrapAll('<div class="wrapped" />');
});

从 jQuery UI 文档来看,你不需要包装 div 上的任何类,我只是包含了一个以方便这个 jsFiddle 演示:

演示:http: //jsfiddle.net/StUWc/1/

只是为了彻底,在 wrapAll 函数之后,你的 DOM 变成了可以用这个标记表示的东西:

<h2>HEADER</h2>
<div class="wrapped">
  <fieldset>
    <legend>Prices</legend>
    <div class="prices">
        <div class="productline" >
            <label>Price:</label>
               <div  class="amount">$97.50</div>
        </div>
    </div>
  </fieldset>
</div>

<h2>HEADER</h2>
<div class="wrapped">
  <fieldset>
    <legend>Prices</legend>
    <div class="prices">
        <div class="productline" >
            <label>Price:</label>
               <div  class="amount">$105.50</div>
        </div>
    </div>
  </fieldset>
</div>
于 2012-07-05T05:34:30.960 回答