简体   繁体   中英

RemoveClass and AddClass not working

I think this may be because these elements didn't originally have the DOM element. I have tried using events and then a propagation tool, but it's still not working :(

I want it so that when you click one of the items, it removes the underline from all items, and then adds it to the item that you just clicked, but in this case it keeps it underlined. To test just use the fiddle link and click on the first "A" , and then the second bigger "A"

( JSFiddle )

 $(document).ready(function() { $("li.big").on("click", function(e) { $("li>a.underline").removeClass("underline"); $("li.big").addClass("underline"); e.stopPropagation(); }); $("li.default").on("click", function(e) { $("li>a.underline").removeClass("underline"); $("li.default").addClass("underline"); e.stopPropagation(); }); }); 
 a { text-decoration: none; } .underline { text-decoration: underline; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="nav navbar-nav"> <li> <div class="raisetext">Raise Text:</div> </li> <li class="default"><a href="#" class="underline">A</a> </li> <li class="big"><a href="#" style="font-size: 20px;">A</a> </li> <li class="bigger"><a href="#" style="font-size: 26px;">A</a> </li> </ul> 

To add to Sushils answer, it sounded like the anchors were appended. So, just in case the anchor tags were dynamically appended to the page:

$(document).ready(function() {
  $("li").on("click","a", function() {
    $("li > a").removeClass("underline");
    $(this).addClass("underline");
  });
});

you can simply use $('a').on('click', function(){ instead of the li.big and li.default since they're all links.

try this

$(document).ready(function() {

    $('a').on('click', function(){
        $('a').removeClass('underline');
        $(this).addClass('underline');
    });
});

here's a working JSFIDDLE

note: this will apply to all the links on the page. if you don't wan't it to apply to all the links, then you can use a class.

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