jQuery无法将类添加到动态添加的内容中 [英] jQuery cannot add class to dynamically added content

查看:61
本文介绍了jQuery无法将类添加到动态添加的内容中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果我动态添加内容,则必须使用on()将事件处理程序用于父元素.但是当我在动态添加的内容上使用addClass时,该类立即消失.

这是HTML的相关部分(只是为了确保我不会错过错别字):

<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>

以下是添加动态元素的代码:

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();
});

但是当我单击该元素时,类的添加时间仅为0.1秒(必须将.categories_selectedbackground-color切换为红色以查看它),但我不明白为什么.

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

因此,如果我单击动态创建的元素之一,它将显示文本(例如,"All"(不是从php提取的,但是您知道了)),但不会永久添加该类.

我只是绝对要确保我没有错过任何真正愚蠢的东西,这是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;
}

我在这里想念东西吗?

使用jquery-1.10.2.js

解决方案

您的代码还可以,我在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.

这篇关于jQuery无法将类添加到动态添加的内容中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆