将div拖动到表中并获取单元格的id

时间:2014-10-06 15:25:39

标签: jquery draggable

我正在尝试提醒我正在拖动某些内容的表格单元格的ID。我把各种各样的例子拼凑在一起,虽然我觉得我很接近,但我并不完全在那里。任何指针都感激不尽,谢谢!

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Draggable - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
  <style>
  #draggable { width: 150px; height: 150px; padding: 0.5em; }
  </style>
  <script>
  $(function() {
    $( "#draggable" ).draggable();

    $('.drop').droppable({
        accept: ".nodrop",
        tolerance: "pointer",
        snap: ".drop",


  }
  drop: function (event, ui) {
            var parenttd = $(ui.draggable).closest('td').attr('id');

 alert("parenttd=" + parenttd);

  );
  </script>
</head>
<body>

<div id="draggable" class="ui-widget-content">
  <p>Drag me around</p>
</div>

<br /><br />
<table style="width:600px;" border="1" cellspacing="0">
  <tr>
    <td id="1" align="middle"><h1>1</h1></td>
    <td id="2" align="middle"><h1>2</h1></td>
  </tr>
  <tr>
    <td id="3" align="middle"><h1>3</h1></td>
    <td id="4" align="middle"><h1>4</h1></td>
  </tr>
</table>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

首先,你的js代码中有很多错误。

以下是非常好的解释:http://jqueryui.com/droppable/

这可以解决您的问题。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Draggable - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
  <style>
  #draggable { width: 150px; height: 150px; padding: 0.5em; }
  #droppable td{ width: 200px; height: 200px; padding: 0.5em; }
  </style>
  <script>
  $(function() {
    $( "#draggable" ).draggable();

    $('#droppable td').droppable({
        drop: function (event, ui) {
            var parenttd  = $(this).attr('id');
            alert("parenttd=" + parenttd);
        }

  })
});


  </script>
</head>
<body>

<div id="draggable" class="ui-widget-content">
  <p>Drag me around</p>
</div>

<br /><br />
<table id="droppable" border="1" cellspacing="0">
  <tr>
    <td id="1" align="middle"><h1>1</h1></td>
    <td id="2" align="middle"><h1>2</h1></td>
  </tr>
  <tr>
    <td id="3" align="middle"><h1>3</h1></td>
    <td id="4" align="middle"><h1>4</h1></td>
  </tr>
</table>

</body>
</html>