两行相似的代码,一行有效,另一行无效。为什么不?

时间:2011-03-07 07:21:47

标签: javascript jquery dom syntax

我有这两行:

$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

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

使用$target_box.children

替换$target_box.find中的“儿童”

孩子选择直接孩子,同时在节点内找到外观/发现!!

答案 2 :(得分:1)

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

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

(是的,这违反了OP的评论*“那么有没有改写第1行,所以它以$ target_box开头。对于拥有更多可读代码的意图?”*直到我发布之后才看到它。 )

相关问题