当前位置: 动力学知识库 > 问答 > 编程问答 >

how to access this with jQuery?

问题描述:

I'm newbie to jQuery.so please tell me how to use this variable inside the loop.

For eg.

this.tblsize=10;

$.each([1,2],function(idx,val){

console.log(this.tblsize)

});

Output

undefined

undifined

But I need to get output as 10 10.

Anything wrong?

网友答案:

Just dont use this, use any other variable name:

var tblsize=10;
$.each([1,2],function(idx,val){
console.log(tblsize)
});
网友答案:

You need to utilize closure in order to access this from a different scope:

this.tblsize=10;
var self = this;
$.each([1,2],function(idx,val){
    console.log(self.tblsize)
});
网友答案:

You can't use this inside the anonymous function since it's another scope.

This should work

    this.tblsize=10;
    var thisref = this;

    $.each([1,2],function(idx,val){
    console.log(thisref.tblsize)
    });
网友答案:

Just Try with the following example :

<ul>
    <li>foo</li>
    <li>bar</li>
</ul>

$( "li" ).each(function( index ) {
  console.log( index + ": "" + $(this).text() );
});

I think this may help you to resolve your problem.

网友答案:

Lets see you code:

this.tblsize = 10;

Here, the tblsize value has been specified outside the scope of $.each()

Next if you do:

$.each([1,2],function(idx,val){
      console.log(this)
});

You will get the values like 1 & 2, since this here refers to the inner result scope of $.each() method. So, in your case, if you do something like this.tblsize, you would surely get something like undefined since there's no variable with this name inside each.

Hence, to get what you want you can simply create a circular global object, store the outside scope variable in it and access it inside the $.each() method, like:

this.tblsize = 10;

// circular global object
var table_size = this;

$.each([1,2],function(idx,val){
      console.log(table_size.tblsize);        // way 1
      console.log($(table_size)[0].tblsize);  // way 2
});
网友答案:

Create a copy of this before calling the $.each. Within $.each this will refers to elements of $.each().

this.tblsize=10;
var $this = this;
$.each([1,2],function(idx,val){
    console.log($this.tblsize)
});

http://api.jquery.com/each/

分享给朋友:
您可能感兴趣的文章:
随机阅读: