【问题标题】:Traversing with jQuery and matching elements使用 jQuery 遍历和匹配元素
【发布时间】:2014-02-26 15:12:33
【问题描述】:

我在点击标签行时克隆了一个 div(带有一个 h3、一个段落和一个可点击的标签行)并将 div 附加到我的侧边栏。有几个具有相同结构的 div,当一个 div 已经被克隆时,我想确保该 div 没有被第二次克隆。为了做到这一点,我试图将其标签行被点击的 div 的 H3 文本与已经被克隆的 div 的 H3 文本相匹配。如果匹配,我会弹出一条警告消息,并且不会将克隆的 div 附加到侧栏。

这是我的代码:

$(this).click(function(){ // where $(this) is the tag line

var clone = $(this).parents('.full_result').clone(); // on the click of the tag line, find the parent whose class is .full_result and clones it (.full_result is the class of all divs)

var jobsH3 = $(this).parents('.full_result').find('h3').text(); // returns the text of the H3 that is contained in the same div as the clicked tag line

var middleColumnInnerDiv=$('#middle_column').find('.full_result').find('h3').text(); // returns the text of all h3 whose divs have been cloned to the side bar(sidebar id= #middle_column)

//下面是魔法应该发生的地方,但我无法让它发挥作用。尝试了几种选择器和方法。 :contains 只是其中之一。

  $(this).parents('.full_result').find('h3').each(function(){
      if('middleColumnInnerDiv:contains(jobsH3)'){ // this line is giving me a headache
     alert('You already saved this information');   
      } else {
           clone.appendTo('#middle_column').hide().fadeIn(750);
    }               
   });
};

非常感谢任何帮助!

【问题讨论】:

    标签: javascript jquery jquery-traversing


    【解决方案1】:

    您缺少$ Jquery 表示法。试试这个$("middleColumnInnerDiv:contains('.jobsH3')")

    【讨论】:

    • 谢谢,苏巴什。但这行不通。也不知道为什么你添加了一个“。”到jobsH3,因为它不是一个类而是一个变量。
    • 创建一个 FIDDLE 以便于调试。
    • 谢谢。我解决了这个问题。我现在正在按 ID 匹配元素。通过文本匹配元素是有问题的,因为添加到侧边栏的每个新 h3 都被连接起来,形成一长串文本。我必须匹配字符串,而不是文本本身。通过匹配 ID,解决问题要简单得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2020-04-19
    相关资源
    最近更新 更多