I have this simple code for debugging (there's more, but this is the stripped version):
function calc(container) {
console.log(container);
return 100;
};
$(".replace").text(calc(this));
The console is just returning the window
, not the element. Why is this? Is there something that prevents jQuery/JavaScript from returning the element?
I have this simple code for debugging (there's more, but this is the stripped version):
function calc(container) {
console.log(container);
return 100;
};
$(".replace").text(calc(this));
The console is just returning the window
, not the element. Why is this? Is there something that prevents jQuery/JavaScript from returning the element?
-
2
Yes,
this
iswindow
in that scope. – elclanrs Commented Nov 6, 2013 at 2:36
5 Answers
Reset to default 2Because the calc
method is not invoked within the element's context, you need to use something like
$(".replace").text(function(){
return calc(this)
});
in this case the calc
method is invoked within a callback method where this
refers to the current element.
Demo: Fiddle
this
here refers to the window object
$(".replace").text(calc(this));
you should use
$(".replace").text(function(){
return calc(this); // here this refers to the current element with class replace
});
Read this keyword
In the global context, this
is window
.
> this === window
true
What you want is probably something like this:
var $replace = $(".replace");
$replace.text(calc($replace));
Just another option, since you are looking for the element just use your function reference itself as the argument of text.
function calc() {
console.log(this);
return 100;
};
$(".replace").text(calc);
That's right.
Because when you call that function the current scope is window.
If you want to use the element, use function parameter instead.
Refer jQuery set text
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246291a4618426.html
评论列表(0条)