Jquery,在ajax成功函数中操作数据

jquery, manipulate the data in an ajax success function

本文关键字:操作 操作数 数据 函数 成功 ajax Jquery      更新时间:2023-09-26

在qwerty.php中,我能够用ajax加载test.php,我还想操纵成功函数中加载的数据,但它似乎不起作用。

在qwerty.php我的代码是

<div class="qwerty">qwerty</div>
<script src="jquery.js"></script>
<script>
$(function(){
$.ajax({
    type: 'GET', 
    url: 'test.php', 
    success: function(data, textStatus, jqXHR) {
        $(data).find('.test1').click(function(){$(this).toggle();});
        $('.qwerty').before(data);
    }
});

});
</script>

在test.php中我有:

<div class="test1">test1</div>
<div class="test2">test2</div>

所以我的数据在div"qwerty"之前正确加载,但是当我点击"test1"时,什么都没有发生。

它不工作,因为你附加onclick到$(data),但插入data到DOM。试试这个:

success: function(data, textStatus, jqXHR) {
    var el = $(data);
    el.find('.test1').addBack().filter('.test1').click(function(){$(this).toggle();});
    $('.qwerty').before(el);
}

我使用find(...).addBack().filter(...)来查找匹配您的选择器的所有元素。find()将只发现test1和test1的子元素具有类testone。filter()只会过滤所有的根元素,所以如果你有子元素,它不会在这些元素中搜索。因此构造find(...).addBack().filter(...)

使用filter(),因为它是返回的字符串

试试这个

success: function(data, textStatus, jqXHR) {
    $('.qwerty').before(data);
    $(data).filter('.test1').click(function(){$(this).toggle();});
}

首先附加数据并在委托事件上使用…

success: function(data, textStatus, jqXHR) {
    $('.qwerty').before(data);
}
}); //ajax end

$('.qwerty').on('click' , '.test1' ,function(){
    $(this).toggle();
});