【问题标题】:Two lines of similar code, one works, the other doesn't. Why not?两行类似的代码,一行有效,另一行无效。为什么不?
【发布时间】:2011-03-07 07:21:46
【问题描述】:

我有这两行:

$target_box.children('a.ajax_trigger_title').addClass('opened_post_title');
jQuery('#'+$target_box.attr('id')+' a.ajax_trigger_title').addClass('opened_post_title');

第一行不起作用,但第二行起作用。为什么?

如果你必须知道,这里是相关的 HTML:

<div class="box" id="30" style="position: absolute; left: 350px; top: 0px; margin-top: 10px; margin-right: 10px; margin-bottom: 10px; margin-left: 10px; ">
    <h2>
        <a class="ajax_trigger_title" id="open_30" href="http://keepskatinbro.com/2011/01/20/some-highlights-from-ksbs-throw-down-show-down/" rel="30">
            <span>Highlights from KSB’s “Throw Down Show Down”.</span>
        </a>
    </h2>
</div>

$target_box 是类为“.box”的div

【问题讨论】:

    标签: javascript jquery dom syntax


    【解决方案1】:

    因为 .children() 只选择直接的孩子。其中 "#X Y" 选择 ID 为 X 的元素的所有后代 Y。

    【讨论】:

    • 哦,我明白了!那么有没有办法重写第 1 行,使其以$target_box. 开头,以使代码更具可读性?
    • @trusktr 将children 替换为find
    【解决方案2】:

    $target_box.children 中的“孩子”替换为$target_box.find

    children 选择直接子节点,而 find 在节点内查找/查找!!

    【讨论】:

      【解决方案3】:

      或者,您可以使用$target_box 作为context

      $('a.ajax_trigger_title', $target_box).addClass(...);
      

      (是的,这违反了 OP 的评论 *“那么有没有办法重写第 1 行,使其以 $target_box 开头。为了让代码更具可读性?”* 直到我发布后才看到它。 )

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-15
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2014-01-29
        • 2012-03-05
        • 1970-01-01
        相关资源
        最近更新 更多