简体   繁体   中英

jQuery/Javascript: What's wrong with my 'If'?

I have a little hunk of my code here:

if(".level-0.find('.children').length == 1"){
     $(".level-0 > a").attr("href", ""); 
 };

Basically I'm saying "If Level 0 has a class of '.children', don't rewrite the HREF in it's link!"

The problem is that it ALWAYS overwrites the HREF, as if there were no conditional. I've changed that "== 1" to "== 10000000" or "20" or "15" and it ALWAYS overwrites the HREF. It's just acting as if there's no conditional statement. I'm sure this is a synatx goof, but I can't see it.

Again, thanks for helping a n00b stumble his way towards minimal competency. Here's the code we're looking to change, just for context.

<li class="level-0 page_item page-item-264"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=264" title="Ca$h Rulez">Ca$h Rulez</a>
<ul class='children'>
    <li class="level-1 page_item page-item-266"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=266" title="1994">1994</a></li>
    <li class="level-1 page_item page-item-268"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=268" title="1995">1995</a></li>
    <li class="level-1 page_item page-item-270"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=270" title="1996">1996</a></li>
    <li class="level-1 page_item page-item-272"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=272" title="1997">1997</a></li>
    <li class="level-1 page_item page-item-274"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=274" title="1998">1998</a></li>
    <li class="level-1 page_item page-item-276"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=276" title="1999">1999</a></li>
    <li class="level-1 page_item page-item-278"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=278" title="2000">2000</a></li>
    <li class="level-1 page_item page-item-280"><a href="http://www.domain.com.php5-15.dfw1-1.websitetestlink.com/wordpress/?page_id=280" title="2001">2001</a></li>
</ul>
</li>

Shouldn't it rather be

if ($(".level-0").find('.children').length == 1) {
    $(".level-0 > a").attr("href", ""); 
}

?

Late friday maybe? :)

You cant use your condition there like you do, because if you have more than 1 .level-0 , you got no relation between .level-0 and its >a
If your condition matches only 1 time, all .level-0>a inside the document will be accessed.

$('>a',$(".level-0").has('.children'))

...will select all child- <a> 's of .level-0 , if .level-0 contains at least 1 .children

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