简体   繁体   中英

Two lines of similar code, one works, the other doesn't. Why not?

I have these two lines:

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

The first line doesn't work, but the second one does. Why?

Here's the relevant HTML if you must know:

<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 is the div with the class of ".box"

Because .children() only selects the immediate children. Where as "#XY" selects all descendants Y of element with ID X.

replace "children" in $target_box.children with $target_box.find

children selects immediate children while find looks/finds inside the node!!

Alternatively, you could use $target_box as the context :

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

(Yes this violates OP's comment *"So is there someway to rewrite line #1 so that it starts with $target_box. for intents of having code that is more readble?"* Didn't see it until after I posted.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM