简体   繁体   中英

jQuery cannot add class to dynamically added content

I know that if I add content dynamically I have to use an event handler for a parent element using on(). But when I use addClass on dynamically added content the class immediately disappears.

Here's the relevant part of HTML (just to make sure I don't missed typos):

<div id="training_management_categories_items">
    <ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul">
    </ul>
</div>

Here's the code that adds the dynamic elements:

function GetCategories()
{
  var url = './ajax/training_management_data.php';
  $('#training_management_categories_items').html('<ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul"></ul>');
  $('#training_management_categories_items_ul').append(' \
    <li class="training_management_categories_list"> \
      <a href="" class="training_management_categories_list_a" id="training_management_categories_list_a_all">All</a> \
    </li> \
  ');
  $.ajax({
    url: url,
    type: "POST",
    data: "action=get_categories",
    dataType: 'json',
    success: function (data) {
      $.each(data, function(index, data) {
        $('#training_management_categories_items_ul').append(' \
          <li class="training_management_categories_list"> \
            <a href="" class="training_management_categories_list_a" id="training_management_categories_list_a_'+data.id+'">'+data.name+'</a> \
          </li> \
        ');     
      });
    }
  });
}

$(document).ready(function() {
    GetCategories();
});

But when I click the element the class is added for just like 0.1 seconds (had to switch the background-color for .categories_selected to red to see it) and I don't get why.

$('#training_management_categories_items').on('click', '.training_management_categories_list_a', function () {
    $(this).addClass('categories_selected'); // DOESN'T WORK
    alert( $( this ).text() ); // THIS WORKS
});

So if I click on one of the dynamically created elements it shows the text (for example "All" which is not fetched from php but you get the idea) but doesn't permanently add the class.

And just for me making ABSOLUTE sure I didn't miss anything really really stupid, here's the CSS:

a.training_management_categories_list_a {
    text-decoration:none;
    display:block;
    background-image:url("img/icons/folder.png");
    background-size:16px 16px;
    padding-left:25px;
    background-repeat:no-repeat;
    font-size:9pt;
    background-position:4px 2px;
    height:20px;
    padding-top:2px;
}

a.training_management_categories_list_a:hover {
    background-color:#aaa;
}

a#training_management_categories_list_a_all {
    font-weight:bold;
}

a.categories_selected {
    background-color:#aaa !important;
}

Am I missing something here?

Edit: using jquery-1.10.2.js

Your code is ok, I tried out that in a jsfiddle: http://jsfiddle.net/carloscalla/n42m6gpf/1/

What is happening is that the color you are setting in the a.categories_selected is the same color it was before (in the hover), I changed it to yellow background-color: yellow !important; so you realize it is working. Try clicking the link and you will see how it changes the background color before the alert pops up.

UPDATE: Just for people looking for answers to know. Anchor element reloads the page so styles will be set to the initial ones. You are using ajax so you don't want the page to be reloaded, therefore you should pass an e parameter to your function and use e.preventDefault() on your onClick function to avoid the default behaviour of anchor tag.

Maybe this works for you, change this line:

$(this).addClass('categories_selected'); // DOESN'T WORK

to this one:

$(this).parent().find('.training_management_categories_list_a').addClass('categories_selected');

I don't know why but I have seen this problem before and solved with this way.

Have you tried inspecting the element to see if the class is present? That usually helps me identify what's going wrong. It might be that another class is overriding the properties from your 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