简体   繁体   中英

Why is jQuery-UI draggable not working?

I have the following code and am trying to allow a point (img and text within a div) to be draggable once it is created.

<div id="container">
    <img src="images/aoi.png" alt="" />
    <div id="point_panel">
        <form>
            <fieldset id="point_container">
                <img id="point" src="images/point.png" alt="" /><input id="point_name" type="text" />
            </fieldset>
        </form>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        $('#point').click(function() {
            var alt = $('#point_name').val();
            $('#container').append('<div class="points"><img src="images/point.png" alt=\"'+alt+'\" />'+alt+'</div>');
        });
        $('.points').draggable({ containment: '#container', stack: '.points', opacity: 0.5, zIndex: 100 });
    });
</script>

User clicks on the img in the form, a new div with the same img and text is created. That div should then be draggable anywhere within the div with the id of container.

When I create the point, it cannot be dragged. Anything missing from my code?

Thanks

Try this:

$(document).ready(function() {
    $('#point').click(function() {
        var alt = $('#point_name').val();
        var el = $('<div class="points"><img src="images/point.png" alt=\"'+alt+'\" />'+alt+'</div>');
        $('#container').append(el);
        $(el).draggable({ containment: '#container', stack: '.points', opacity: 0.5, zIndex: 100 });
    });
});
    $(document).ready(function() {
            $('#point').click(function() {
                var alt = $('#point_name').val();
                $('#container').append('<div class="points"><img src="images/point.png" alt=\"'+alt+'\" />'+alt+'</div>');
                //bind draggable to last inserted div 
                $('#container').find('.points:last').draggable({ containment: '#container', stack: '.points', opacity: 0.5, zIndex: 100 });            
             });
            $('.points').draggable({ containment: '#container', stack: '.points', opacity: 0.5, zIndex: 100 });
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM