如果所有元素具有相同的ID,则使其可拖动

问题描述:

使用JQuery,当元素都具有相同的ID时,我试图使多个元素可拖动.可以使用JQuery做到这一点吗?

Using JQuery, I'm trying to make multiple elements draggable when the elements all have the same ID. Is is possible to do this using JQuery?

(在这里,有两个div,其ID为可拖动",我想将它们都拖放).

(Here, there are two divs with the id "draggable", and I'd like to make both of them draggable.)

相关代码在这里: http://jsfiddle.net/zcJwu/

<!doctype html>

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

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


</body>
</html>​

HTML 页面中的

ID 应该是唯一的.

如果提供重复的 Id ,并将其用作选择器,它将始终选择遇到的第一个元素.So it will never work.

If you give duplicate Id's and use that as a selector, it will always select the first element that it encounters.. So it will never work.

尝试使用课程.

您可以为所有要拖动的元素提供名为draggable的类.

You can give the class called draggable to all the element you want to drag.

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

检查小提琴

Check Fiddle