سؤال

I am using jqueryui droppable and I am having trouble getting the end result.

jquery:

 $( "ol" ).droppable({
  activeClass: "ui-state-default",
  hoverClass: "ui-state-hover",
  drop: function( event, ui ) {
    $( "<li></li>" ).text( ui.draggable.text() ).appendTo( this );

  }

What does this line do?

 $( "<li></li>" ).text( ui.draggable.text() ).appendTo( this );

is correct to say "Take the text that is in the given "li" and append it to the object "this"?

my problem is that if i loop through the ol and get the id of all the li's in the ol, i get undefined.

 $('#butSub').click (function()
 {
            var data = "";
            $('ol').each(function()
            {

                    var olId = $(this).attr('id');
                    $('#'+olId+' li ' ).each(function()
                    {
                            alert($('#'+olId+' li').attr('id'));
                    })
            })
هل كانت مفيدة؟

المحلول

Your primary question, what does this line do

$( "<li></li>" ).text( ui.draggable.text() ).appendTo( this );

Can be broken down as follows

$( "<li></li>" ) // create an new, empty li element
    .text( ui.draggable.text() ) // set the text of the new li to the text of the dragged item
    .appendTo(this); // append the new li to "this"

In this case, this refers to the ol that you're attaching the droppable behaviour to

The next bit of your code

$('ol').each(function()
{
    var olId = $(this).attr('id');
    $('#'+olId+' li ' ).each(function()
    {
        alert($('#'+olId+' li').attr('id'));
    })
})

Has a few things I wanted to point out. First off, you dont need to get the id of the ol and use that id to find child li, you can just scope to the correct element, so change this:

var olId = $(this).attr('id');
$('#'+olId+' li ' ).each(function()
{ ... }

to

$('li', this).each(function() 
{ ... }

In the above, this is the ol, so $('li',this) finds all li within the ol.

Lastly,

alert($('#'+olId+' li').attr('id'));

should be

alert($(this).text());

Now, this is the li you're looping over (yes, javascript scoping and the this keyword can get confusing). Also, as you never gave the newly generated li an id, there wont be any, so I changed it to read the .text(). If you intended to give your dynamic li elements an id, you can change the original line to:

$( "<li></li>" ).text( ui.draggable.text() ).attr('id','someId').appendTo( this );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top