开发者

Getting the jQuery object/reference

Here I'm wrapping an HTML tag with another tag '$holder' below.

  $holder = $('<div />')
 开发者_高级运维   .addClass('joverlaytext')
    .css({
        position:'relative', 
    });
  $(this).wrap($holder);

Now after this statment how to get the object/reference to this newly created HTML element, ie. jQuery obj of '$holder'


Just continue the chain, e.g.:

$(this).wrap($holder).show();

If you look at the manipulation methods documentation, .wrap(elem) returns a jQuery object, so chaining or

var result = $(this).wrap($holder);

will work.


Just continue to use $holder as normal, placing it in a wrap function will not change it's jQuery object reference. So you could do this.

  $holder = $('<div />')
    .addClass('joverlaytext')
    .css({
        position:'relative', 
    });
  $(this).wrap($holder);
  $holder.show().doTheFunkyChickenDance();

Also as always, try not to use $(this), instead cache the object lookup by doing this

var $this = $(this);
// then just use $this as normal so
$this.wrap($holder);

Using the var keyword is also important, as it creates a locale variable rather than a global variable which should be avoided to stop banging heads on walls later down the track.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜