开发者

jQuery .data() to store id for later access? or other method?

I开发者_如何学JAVA am trying to append a div to the body, so

$('<div>').appendTo(document.body);

However instead of giving that div an ID attribute association so I can access it later, I would like to use jQuery.data() to access that div later so actions can be applied to it.

$('<div>').data('#myid').appendTo(document.body);

now how do I access it later.


var later = $('<div>').appendTo(document.body);
// ...
later.actions();


This is sounds pretty wierd. Even if you set some kind of id over the data- expando, you wouldn't know where to access it later. You don't have a reference to the element which contains that data property.

Best way to keep a reference for a newly created node is, to store it in a local variable.

var $newdiv = $('<div>').appendTo(document.body);

Referrencing to your comment

Almost all jQuery methods return the wrapped set containing jQuery objects. These objects in turn, hold a reference to the DOM node. You can think of it like a bridge. On the one side is your ECMAland (Javascript) and on the other side, its DOMland. If you cross that bridge to get a reference from a DOM node (which is expensive btw), you can (and should!) store that reference in ECMAland. The next time you want to access the DOM node, you don't need to cross the bridge and pay the expensive toll, you still have that references and can manipulate the DOM node.


If you must get it later without id simply iterate over every object in the DOM and check whether it's your div.

for (var i = 0; i < document.getElementsByTagName("*").length; i++) {
    if ($(document.getElementsByTagName("*")[i]).data("isMyDiv")) {
         var myDiv = $(document.getElementByTagName("*")[i]);
    } 
}

if (myDiv !== undefined) {
   // do stuff
}

Alternatively you can write efficient code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜