开发者

jQuery $.data(): Possible misuse?

Perhaps I'm using $.data incorrectly.

Assigning the data:

var course_li = sprintf('<li class="draggable course">%s</li>', course["fields"]["name"]);

$(course_li).data('pk', course['pk']);
alert(course['pk']); // shows a correct value

alert($(course_li).data('pk')); // shows null. curious...

course_li is later appended to the DOM.

Moving the li to a different ul:

function moveTo开发者_如何学JAVATerm(item, term) {
    item.fadeOut(function() {
        item.appendTo(term).fadeIn();
    });
}

Trying to access the data later:

$.each($(term).children(".course"), function(index, course) {
      var pk = $(course).data('pk');
      // pk is undefined
      courses.push(pk);
});

What am I doing wrong? I have confirmed that the course li on which I am setting the data is the same as the one on which I am looking for it. (Unless I'm messing that up by calling appendTo() on it?)


When you store the data:

$(course_li).data('pk', course['pk']);

you're creating an element but not saving it, so it's lost. Your alert test test the wrong value; it should be:

$(course_li).data('pk', course['pk']);
alert($(course_li).data('pk'));

which is null. Consider:

$(course_li);
$(course_li);

This creates two different elements with source equal to course_li, which are then promptly lost. What you need to do is create the element first, then work with that single element (i.e. don't call $(course_li) more than once). For example,

var course_li = $(sprintf('<li class="draggable course">%s</li>', 
                          course["fields"]["name"]));
course_li.data('pk', course['pk']);
parent.append(course_li);

Note that course_li now holds an element, rather than a string.


try checking to see if the element being created by this call:

$(course_li)

is a single 'li' element, or a div. From the doco:

When the HTML is more complex than a single tag without attributes, as it is in the above example... snip ...Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in

So it's probably creating a div that you are assigning the data to, so when you select the 'li' itself, you are getting a child of the actual element that you set the data on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜