dongyao2129 2014-03-12 19:07
浏览 44
已采纳

使用AJAX刷新页面时运行onLoad脚本

I have a piece of jQuery for making items draggable:

$( ".draggable" ).draggable();});

Works fine here, you can drag the words around

It works by running the script which adds some classnames to any span with class="draggable" and it does this on page load, so they look like this:

<span class="draggable ui-draggable" style="position: relative; left: -129.625px; top: -137.625px;">confident</span> 

This issue is that pressing the green button refreshes the wordbank with AJAX, it calls in a new file, wordbank.php and every time you press it'll generate a fresh pool of words for you.

But because of that, once you've refreshed the AJAX it doesn't run the script again so the dragging doesn't work.

How can I get the script to rerun with AJAX?

  • 写回答

2条回答 默认 最新

  • douxieshang5577 2014-03-12 19:15
    关注

    By inspecting the newly created elements you can see that they are missing the ui-draggable class. You need to call $( ".draggable" ).draggable(); again to bind the new/dynamic elements.

    I think the best way to do this is in the success or complete callback of your AJAX request, you can use this line:

    $('.draggable:not(.ui-draggable)').draggable();

    to bind any words that are new and DON'T already have the ui-draggable class.

    Since you're already using jquery you should take advantage of their ajax method:

    function refreshWords()
    {
         $.ajax({
            url: "wordbank.php",
            success: function(data){
                $("#wordbank").html(data);
                $('.draggable:not(.ui-draggable)').draggable();      
            }
         });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?