简体   繁体   中英

jquery, manipulate the data in an ajax success function

In qwerty.php I'm able to load test.php with ajax, I also want to manipulate the data loaded in the success function but it doesn't seem to work.

In qwerty.php my code is

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

and in test.php I have :

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

so my data is loaded correctly before the div "qwerty" but when I'm clicking on "test1" nothing happen.

use filter() since its a string that is returned

try this

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

updated

append the data first and use on delgated event...

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


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

it doesn't work because you attach onclick to $(data) but insert data into the DOM. try this:

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

I used find(...).addBack().filter(...) to find ALL elements matching your selector. find() will find only child elements of test1 and test 1 having the class test one. filter() will only filter all the root elements, so if you have children elements, it won't search within those. thus the construct find(...).addBack().filter(...)

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