Calling Javascript function after loading an AJAX page

两盒软妹~` 提交于 2019-12-12 03:12:30

问题


I'm not a programmer so I apologize if my question doesn't make a lot of sense.

But basically I have one page index.php that has a set of filters (by project, year, month) and after pressing submit sends the variables to filterData.php to be used in some SQL statements.

The results in the form of a table of image thumbnails are returned to a div in index.php. What I want to do is have it so when the user clicks on an image the border color will change to highlight the current object.

<script type="text/javascript">
$(document).ready(function () {
    $('.thumbnail_small').click(function(){
        $(this)
            .css('border-color','#000')
            .siblings()
            .css('border-color','#ccc');
    });
});
</script>

^ That is the script I have right now and it works if the table of thumbnails is hardcoded into index.php. Once I have the table loaded through filterData.php, it doesn't work anymore.

What is the reason for this and how can I work around it?


回答1:


Once I have the table loaded through filterData.php, it doesn't work anymore.

Use live or better on depending on version of jQuery you are using:

$('#mainContainer').on('click', '.thumbnail_small', function(){
    $(this)
        .css('border-color','#000')
        .siblings()
        .css('border-color','#ccc');
});

Or

$('.thumbnail_small').live('click', function(){
    $(this)
        .css('border-color','#000')
        .siblings()
        .css('border-color','#ccc');
});

For elements that are added later or dynamically, you got to use live or on.



来源:https://stackoverflow.com/questions/9556200/calling-javascript-function-after-loading-an-ajax-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!