【问题标题】:Selecting element to copy using jQuery Clone使用 jQuery 克隆选择要复制的元素
【发布时间】:2010-11-12 22:30:59
【问题描述】:

我有一个指南,其中每一章都位于 UL 的单独 LI 中。我正在尝试使用 jQuery Clone 函数搜索包含所有这些“章节”LI 的父 UL,并返回那些包含特定文本的章节。

现在,我得到了奇怪的结果,可能是因为它复制了最小的子元素,而不仅仅是整个 div。

此外,这些章节 LI 中的每一个都应该只返回一次。

  • makeIntoSldieshowUL - 包含所有“章节”的 UL
  • slideShowSlide - 每个“章节”的类名
  • searchResultsArea - 添加包含文本的“章节”的 Div

到目前为止我有:

$("#makeIntoSlideshowUL").find(".slideShowSlide:contains('" + $(this).val() + "')").clone().appendTo("#searchResultsArea");

为了让您了解我要克隆的内容,这里有一个简短的示例

<ul id="makeIntoSlideshowUL">
<li  class="slideShowSlide" id="0">
    <div class="topicTitle">Cardholder responsibilities</div>
    <p>Cardholders are responsible for ensuring proper use of the card. If your division or department has approved you for a Pro-Card, you must use the card responsibly in accordance with the following requirements:</p>
    <ul>
        <li>Purchase items for UCSC business use only</li>
        <li>Never lend or share your Pro-Card</li>
        <li>Purchase only allowable goods and services</li>
    </ul>
</li>
<li class="slideShowSlide" id="1">
    <div class="topicTitle"><strong>Restricted and Unallowable Pro-Card Purchases</strong></div>
    <p>Some types of purchases are restricted are not allowed with the Pro-Card.  Disputes with suppliers are initially handled by the Cardholder if, for example, they don't recognize a transaction on their statement, or the amount doesn't match their receipt. The Cardholder is responsible for contacting the supplier immediately to try to resolve the matter.</p>
</li>

【问题讨论】:

  • 您能否提供您正在使用的实际标记的样本/样本?

标签: javascript jquery clone


【解决方案1】:

使用jQuery's .children() method 而不是.find(),因为听起来.slideShowSlide 元素是直接子元素。

$("#makeIntoSlideshowUL").children(".slideShowSlide:contains('" + $(this).val() + "')").clone().appendTo("#searchResultsArea");

或者你可以使用the &gt; child selector

$("#makeIntoSlideshowUL > .slideShowSlide:contains('" + $(this).val() + "')").clone().appendTo("#searchResultsArea");

编辑:在某一时刻,您似乎将章节称为 div。如果它们是 &lt;li&gt; 元素的子元素,您可能需要以下内容:

$("#makeIntoSlideshowUL > li > .slideShowSlide:contains('"...

【讨论】:

  • 它们实际上是列表元素,而不是 div。我猜是习惯的力量。我更新了我的问题以反映这一点。
  • 我还应该注意我试图将 LI 复制到一个 div 中。我已经完成并将#searchREsultsArea 更改为UL 元素。感谢您了解我的双重参考,它帮助我发现了这个错误。
  • @Eric - 所以我认为前两个解决方案对你有用吗?如果没有,请告诉我。另外仅供参考,在 HTML4 中拥有以数字开头的 ID 是无效的。它们必须以字母开头。 :o)
【解决方案2】:

尝试使用 the has 或 contains 选择器

has 不会更改 jquery 堆栈上的当前元素。

$("#makeIntoSlideshowUL")
    .has(".slideShowSlide:contains('" + $(this).val() + "')")
    .clone()
    .appendTo("#searchResultsArea");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多