简体   繁体   中英

Using jQuery to change style of clicked element and removing that style from other elements with same class

EDIT: fixed it! Thanks to those who said to post my HTML - I looked at it, and didn't realize that I had the "appname" class twice.

<li class="<?php echo $apid; ?> appname appname_getinfo appname_<?php echo $apid; ?>">
       <span class="appname"><?php echo $apname; ?></span>
</li>

So, I removed the "" and it works!

Say that I have three elements with a class:

EL ONE

EL TWO

EL THREE

When I click on EL ONE, I would like to make it bold. When I click on EL TWO, it should become bold and EL ONE should become normal weight. When I click on EL THREE next, it should become bold and EL TWO becomes normal weight.

MY SCRIPT:

//// app info ////
$("li.appname_getinfo").click(function(){

    var appID = this.className.split(' ')[0];
    $.get("wishlist/appinfo.php?pw=R32kd63DL&apid=" + appID, function(data){                                
        $("div#appinfo").html(data);                            
    });

    $("div#appinfo").show();

    $(".appname").css("font-weight", "normal");
    $(this).css("font-weight", "bold");


});

I thought that I could set all with class "appname" to normal, then change $(this) to bold, but it doesn't work. (it disallows any to be bold).

first thing, as a rule of thumb, add classes not css directly from js. Secondly you are applying the bold rule to ".appname" and not to "li.appname_getinfo"

Need to use an $().each to add handler to each item. My code is:

$('.appName').each(
  function(index, item){
    $(item).click(
      function(e) {
        $('.appName').css('fontWeight', 'normal');
        $(this).css('fontWeight', 'bold');
    });
});

Tested in Chrome and it seems to work as you describe

While I suspect the problem is, as mentioned above, the mismatch in class-names, one other reason could be because you have a container inside of the "li" element and that container is set to font-weight normal. You are setting the bold on the LI element, but if the element inside of it is normal font, then setting it on the LI won't do anything... eg

...
<style>
span { font-weight:normal; }
</style>
...
<ul>
   <li class="appName"><span>this text will not bold when you bold the LI because it's in a span, and spans are styled with normal font-weight</span>
   </li>
<ul>

Chrome's dev tools will help...

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