且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery无法将类添加到动态添加的内容中

更新时间:2023-02-08 20:15:27

您的代码还可以,我在jsfiddle中进行了尝试: http://jsfiddle.net/carloscalla/n42m6gpf/1/

正在发生的事情是,您在a.categories_selected中设置的颜色与之前(在悬停中)相同的颜色,我将其更改为黄色background-color: yellow !important;,因此您意识到它可以工作.尝试单击该链接,您将在警报弹出之前看到它如何改变背景颜色.

更新:仅适用于寻找答案的人. Anchor元素会重新加载页面,因此样式将设置为初始样式.您正在使用ajax,因此您不希望重新加载页面,因此应将e参数传递给函数,并在onClick函数上使用e.preventDefault(),以避免锚标记的默认行为.>

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.