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

tru*_*ktr 0 javascript syntax jquery dom

我有这两行:

$target_box.children('a.ajax_trigger_title').addClass('opened_post_title');
jQuery('#'+$target_box.attr('id')+' a.ajax_trigger_title').addClass('opened_post_title');
Run Code Online (Sandbox Code Playgroud)

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

如果您必须知道,这是相关的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>
Run Code Online (Sandbox Code Playgroud)

$ target_box是类".box"的div

mrc*_*owl 9

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

  • @trusktr用`find`替换`children` (4认同)