JQuery在通过ajax加载数据库后无法正常工作

3

大家好。

我正在开发一个拥有可拖拽功能的网页。 我找到了一个完全符合我要求的jQuery主题,现在正在使用那段代码。

我没有做很多修改,只是添加了通过ajax和mysql加载数据库的代码。 在加载数据库后,可拖拽的功能就失效了。 我认为这与函数运行顺序有关。 所以,我在拥有可拖拽功能的函数上使用了setTimeout,然后它就起作用了。

但问题是,我必须每隔5秒加载数据库,所以我无法每次加载数据库时都使用setTimeout来调用拥有可拖拽功能的函数。

有没有解决这个问题的方法呢?

这是我使用的代码:

main.php

$(document).ready(function database(){

  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("gallery").innerHTML = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET","db.php",true);
  xmlhttp.send();

   init();
});
setTimeout(function (){

  var $gallery = $("#gallery");
  var $gallery2 = $("#gallery2");
  var $trash = $("#trash");
  var $trash2 = $("#trash2");
  $("li",$gallery).draggable({
    cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
  });
  $("li",$gallery2).draggable({
    cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
  });
  $trash.droppable({
    accept: "#gallery > li",
    classes: {
      "ui-droppable-active": "ui-state-highlight"
    },
    drop: function( event, ui ) {
      deleteImage( ui.draggable );
    }
  });
  $trash2.droppable({
    accept: "#gallery2 > li",
    classes: {
      "ui-droppable-active": "ui-state-highlight"
    },
    drop: function(event, ui){
      deleteImage2(ui.draggable);
    }
  });
  $gallery.droppable({
    accept: "#trash li",
    classes: {
      "ui-droppable-active":"custom-state-active"
    },
    drop: function(event, ui){
      recycleImage(ui.draggable);
    }
  });
  $gallery2.droppable({
    accept: "#trash2 li",
    classes: {
      "ui-droppable-active":"custom-state-active"
    },
    drop: function(event, ui){
      recycleImage2(ui.draggable);
    }
  });
  var recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";
  function deleteImage( $item ) {
    $item.fadeOut(function() {
      var $list = $( "ul", $trash ).length ?
      $( "ul", $trash ) :
      $( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash );
      $item.find( "a.ui-icon-trash" ).remove();
      $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
        $item
        .animate({ width: "100px" })
        .find( "img" )
        .animate({ height: "150px" });
      });
    });
  }
  function deleteImage2( $item ) {
    $item.fadeOut(function() {
      var $list = $( "ul", $trash2 ).length ?
      $( "ul", $trash2 ) :
      $( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash2 );
      $item.find( "a.ui-icon-trash" ).remove();
      $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
        $item
        .animate({ width: "100px" })
        .find( "img" )
        .animate({ height: "150px" });
      });
    });
  }
  var trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";
  function recycleImage( $item ) {
    $item.fadeOut(function() {
      $item
      .find( "a.ui-icon-refresh" )
      .remove()
      .end()
      .css( "width", "96px")
      .append( trash_icon )
      .find( "img" )
      .css( "height", "72px" )
      .end()
      .appendTo( $gallery )
      .fadeIn();
    });
  }
  function recycleImage2( $item ) {
    $item.fadeOut(function() {
      $item
      .find( "a.ui-icon-refresh" )
      .remove()
      .end()
      .css( "width", "96px")
      .append( trash_icon )
      .find( "img" )
      .css( "height", "72px" )
      .end()
      .appendTo( $gallery2 )
      .fadeIn();
    });
  }
  function viewLargerImage( $link ) {
    var src = $link.attr( "href" ),
    title = $link.siblings( "img" ).attr( "alt" ),
    $modal = $( "img[src$='" + src + "']" );
    if ( $modal.length ) {
      $modal.dialog( "open" );
    } else {
      var img = $( "<img alt='" + title + "' width='384' height='288' style='display: none; padding: 8px;' />" )
      .attr( "src", src ).appendTo( "body" );
      setTimeout(function() {
        img.dialog({
          title: title,
          width: 400,
          modal: true
        });
      }, 1 );
    }
  }
  $( "ul.gallery > li" ).on( "click", function( event ) {
    var $item = $( this );
    var $target = $( event.target );
    if ( $target.is( "a.ui-icon-trash" ) ) {
      deleteImage( $item );
    } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
      viewLargerImage( $target );
    } else if ( $target.is( "a.ui-icon-refresh" ) ) {
      recycleImage( $item );
    }
    return false;
  });
  $( "ul.gallery2 > li" ).on( "click", function( event ) {
    var $item = $( this );
    var $target = $( event.target );
    if ( $target.is( "a.ui-icon-trash" ) ) {
      deleteImage2( $item );
    } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
      viewLargerImage( $target );
    } else if ( $target.is( "a.ui-icon-refresh" ) ) {
      recycleImage2( $item );
    }
    return false;
  });
}, 1000);

db.php

    <?php
$host = "localhost";    // 자신의 mysql
$DB_name = "master";    // 데이터베이스 이름
$user = "root";         // 기본 사용자.
$password = "0000";     // apm 기본 암호

$conn = mysqli_connect($host, $user, $password, $DB_name);

if(!$conn){
    echo "fail!\n";
    die('Could not connect: ' . mysqli_error($con));
}

//else
$sql = "select * from sensorlist";
$result = mysqli_query($conn,$sql);
$rowcnt = mysqli_num_rows($result);
$filed_name = array('S_Ultrasonic','S_IR','S_Humidity','S_Temperature','S_Heatindex','S_Light','S_Gas');    //센서 필드명 집합

if($rowcnt == 1){   //right (data가 1행만 들어있는 게 맞는 지 체크)
    while($row = mysqli_fetch_array($result)){
        for($i=0;$i<count($filed_name);$i++){
            if($row[$filed_name[$i]] != NULL){
                echo "<li class='ui-widget-content ui-corner-tr ui-draggable ui-draggable-handle'>";
                echo "<h5 class='ui-widget-header'>" . $filed_name[$i] . "</h5>";
                echo "<a href='images/high_tatras.jpg' title='View larger image' class='ui-icon ui-icon-zoomin'> View larger</a>";
                echo "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a></li>";
            }
        }
    }
    //echo "No sensor";
} else if($rowcnt == 0) {   //data가 하나도 없으면 없다고 출력
    //없다고 출력
    echo "No sensor";
} else {    //이도 저도 아니면 땡!
    //db 에러 출력
    echo "No sensor";
}
mysqli_close($conn);

?>

你尝试过在onreadystatechange处理程序中调用传递给setTimeout的函数,而不是使用setTimeout吗? - guest271314
https://dev59.com/NW3Xa4cB1Zd3GeqPk_wFAndhttps://dev59.com/G3I-5IYBdhLWcg3wiY7aAndhttp://stackoverflow.com/questions/25551103/jquery-drag-and-drop-on-ajax-loaded-div - Alive to die - Anant
setInterval函数 - Samyappa
@guest271314 不是,但我把拖动事件部分移到那里了,它起作用了!谢谢! - Veronica
1个回答

1
如果您动态添加元素,请委托事件,当ajax完成后重新初始化可拖动插件(在onreadystatechange事件的if中执行所有逻辑)。

是的,我实际上正在使用setTimeout来做这件事,但我有点想知道其他的解决方案...(如果有的话)。 - Veronica
我必须每5秒刷新数据库,所以......我不想使用setTimeout每5秒延迟。 - Veronica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接