Using selectors and $(this) in Jquery Ajax response

前端 未结 4 1852
暗喜
暗喜 2021-01-15 01:39

I am wondering how I use Jquery selectors within the Ajax response. My site has a feed and each main block has a unique ID, but I dont want to uniquly ID every div thats wit

4条回答
  •  一整个雨季
    2021-01-15 02:27

    Since the function is an AJAX callback, you can use the context setting:

    $.ajax({
        // ...
        context: this,
        success: function(msg) {
            // Here, 'this' refers to the same object as when ajax() was called.
            var containerId = $(this).parent().attr("id");
            window.alert(containerId);
        }
    });
    

    You can also have the callback function called in the context of the container itself:

    $.ajax({
        // ...
        context: $(this).parent().get(0),
        success: function(msg) {
            // Now, 'this' refers to the container element.
            var containerId = $(this).attr("id");
            window.alert(containerId);
        }
    });
    

提交回复
热议问题