removing div from a jquery sortable
I've developed a "Google-Maps-like" user interface for my intranet where users can add steps to calculated routes and distances. I'm using sortable div
s to reorder steps. Now I want to remove steps, but my JavaScript/jQuery code doesn't work at all. Can you help me?
My jQuery code:
$(document).ready(function() {
$("#sortable").sortable();
$("#sortable").disableSelection();
});
function addStep() {
var temp = $('.template').clone();
$(temp).removeClass("template");
$(temp).addClass("sort");
$('#sortable'开发者_如何学编程).append(temp);
}
function removeStep() {
$(this).closest('div.sort').remove();
$("#sortable").sortable('refresh');
}
And my HTML:
//template to add new step
<div class="template">
<input type="text" name="addressN" value="" class="address" />
<input type="button" class="remove" value="Remove" onclick="removeStep();" />
</div>
//sortable list of step
<div id="sortable">
<div class="sort">
<input type="text" name="Start" value="" class="address" />
</div>
<div class="sort">
<input type="text" name="End" value="" class="address" />
</div>
</div>
<input type="submit" value="Get Route!" onclick="showLocation(); return false;" />
<input type="submit" value="Add Step" onclick="addStep(); return false;" />
Thanks in advance!
There’s something wrong with your addStep()
function. I’ll try to explain by adding some comments to your original code:
function addStep() {
// Here, you store a reference to the jQuery Object containing the clone in the var temp.
var temp = $('.template').clone();
// Here, you wrap temp (which already is a jQuery Object) inside $().
// Fix: replace '$(temp)' by 'temp'
$(temp).removeClass('template');
$(temp).addClass('sort');
$('#sortable').append(temp);
}
After fixing this, plus some additional optimizations, this becomes:
function addStep() {
$('.template').clone().removeClass('template').addClass('sort').appendTo('#sortable');
}
Also, your removeStep()
function incorrectly uses this
. You probably want to do the following:
$.fn.removeStep = function() {
// `this` is now a reference to the jQuery Object on which `.removeStep()` was invoked
this.closest('div.sort').remove();
$('#sortable').sortable('refresh');
// Allow chaining
return this;
}
Now, you can omit the onclick="removeStep();"
from your HTML template, and use something like this in jQuery:
$('.remove').live('click', function() {
$(this).removeStep();
}
精彩评论