开发者

How do I make elements that are generated after page load (ajax) become draggable?

I have a div on my page that gets populated via an ajax call to separate php script every 2000ms. When the user checks a checkbox, the update interval stops and all the items in the div need to become draggable. If I do this without the update interval it works, but once I have the div reloading the items loose their draggability. How can I maintain the their draggable property?

<SCRIPT LANGUAGE="JavaScript">
    $(window).load(function() {
      getScreen ();
    });


    var editMode = false;
    var intervalId = window.setInterval(getScreen ,2000);

    function getScreen () {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            document.getElementById("refresh").innerHTML=xmlhttp.responseText;
          }
        }
        xmlhttp.open("POST","getScreen.php?sid="+<?php echo $sid; ?>,true);
        xmlhttp.send(); 

    }

    function onEditMode(cb) {
      if(cb.checked) { 
        editMode = true; 
        $('.item').draggable( 'enable' );
        window.clearInterval(intervalId);
      }
      else { 
        editMode = false;
        $('.item').draggable( 'disable' );
        intervalId = window.setInterval(getScreen ,2000); 
      }  
    }

    </SCRIPT>
  </head>
  <body>

    <div id="content">      
      <div class="post">            
      开发者_如何学Go   <div id="refresh">
         </div>     
      </div>        
    </div>


You should make items draggable/non-draggable in the Ajax callback after you overwrite the container HTML. Since once is HTML overwritten, any attached DOM listeners are lost.

var refresh = $('#refresh');
refresh.html(xmlhttp.responseText);
$('.item', refresh).draggable('enable');

And yes, as @pduersteler said, jQuery has excellent Ajax facilities. load() method does exactly what you do — loads HTML into a container. $.post() is a way to go.

Also, you'd better replace setInterval with a setTimeout inside the Ajax callback. It will ensure smoother update experience.

var postData = { sid: <?=sid?> };

var container = $('#refresh');

var ajaxCallback = function (data) {
    container.html(data);

    var items = $('.item', container);

    if (editMode) {
        items.draggable('enable');
    } else {
        items.draggable('disable');
        setTimeout(getScreen, 2000);
    }
};

function getScreen() {
    $.post('/getScreen.php', postData, ajaxCallback);
}

getScreen();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜