This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I have a click event attached to an element via JQuery in a loop (loop variable i):
$('#id_'+i).click(function() {ItemClick(i)});
And defined somewhere else:
function ItemClick(x) {
alert(x);
}
As expected, this doesn't work as expected, because of the closure. I'd like to see a different number shown for each different click event, instead I just get the last value of i.
I know I need to turn the i in the closure to something that somehow isn't attached to the scope of the closure, but it eludes me, even after trying various examples. Such as:
$('#id_'+i).click(function() {ItemClick(function(x){return x)(i))});
Is there a neat and concise way of doing this?
EDIT
After looking at the duplicate, I now have two answers (please close the question):
Answer A
$('#id_'+i).data('index',i);
$('#id_'+i).click(
function() {
ItemClick($(this).data('index'));
}
);
Answer B
$('#id_'+i).click(
function(index) {
return function () {
ItemClick(index)
};
}(i)
);
This is a very common javascript issue that occurs because Javascript is closure/scope based, not block based.
You can fix this by creating a closure around your function call.
$('#id_' + i).on('click', function() {
(function (index) {
ItemClick(index);
}(i));
});
jsFiddle Demo
Related
This question already has answers here:
Javascript: Object Literal reference in own key's function instead of 'this'
(5 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Apologies if the terminology is off - javascript isn't my thing.
I have a function:
var input = {
getVal: function () {
return $(this).attr("data-current-val");
},
setVal: function () {
$(this).attr("data-current-val", $(this).val());
},
valHasChanged: function () {
return $(this).val() !== $(this).attr("data-current-val");
}
};
As you can see there is some repetition. Firstly, I repeat the data attribute name several times; secondly, I select a jquery object numerous times.
I've tried to remove the repetition. For instance, in respect of the data attribute, by adding node: "data-current-val" at the top and then calling it with this.node in place of the string. That causes an error, as does trying to define and then use the jquery objectin the same way.
Similarly part of the boolean in valHasChanged $(this).attr("data-current-val"), logically could be replaced by this.getVal but that doesn't seem to work either. Where am I going wrong?!
Any help appreciated.
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 3 years ago.
I am working on some JavaScript code and I run into this syntax that I have never seen and I am trying hard to understand but cannot find good examples.
Can someone please describe what might be going on here?
function onMouseMove(event) {
(function(ev) {
// some piece of code
})(event);
}
This syntax is used to create an inner scope using a function and that function is immediately invoked with the event object.
This question already has answers here:
jQuery document.ready vs self calling anonymous function
(5 answers)
Closed 8 years ago.
I have tested something and it was really strange...
When I use:
jQuery(document).ready(function ($){
console.log($('.box').length);
});
the return value is 4;
If I use this:
(function ($){
console.log($('.box').length);
})(jQuery);
the return value is 0;
(in the same document)
Any explanation for that?
(I have tried to reproduce in jsfiddle but both return same value.)
Your second example will cause the code in the function to run when the whole overall statement is parsed. The jQuery version waits until the DOM has been fully parsed and populated. The two pieces of code are simply different, in other words.
This question already has answers here:
jquery/javascript: function(e){.... what is e? why is it needed? what does it actually do/accomplish?
(4 answers)
What is the purpose of this? (function ($) { //function code here })(jQuery);
(4 answers)
Closed 8 years ago.
In the following code, there are two 'e's, are they about the same object/type or actually about different things?
(function(e) {
var t = {
init: function() {
e(".pic").length && this.show()
}
};
window.Booth = t;
})(jQuery);
Also, I am a little confused with the overall semantics of the code snippet above, any documentation out there can explain it?
In this case, it's an alias for jQuery. Usually people use $, but in this case they didn't.
what you have is an anonymous, self-executing function.
the function is passed the jquery object (which is a function). e(".pic") is the same as $(".pic") or jQuery(".pic") because e is just a reference to jQuery.
This question already has answers here:
What does $(function() {} ); do?
(6 answers)
Closed 9 years ago.
I find the following code in an html document:
<script type="text/javascript">
$(function () {
...
});
I cannot see any intrinsic events like onload = and would like to know how this code is called?
What is the real name and scope of this function and can I call any function defined inside? How?
Whenever you see $ before a function, or $(...).function(...) that usually denotes jQuery.
In the following fiddle I use this code, which is executed on load:
$(function () {
alert("hi!");
});
See here: http://jsfiddle.net/VMZkW/
It is just an anonymous function . In javascript you don't really need to give it a name and because of that after executing once you can never refer it again.
You can have anonymous functions that can be used several times, but not this one. To reuse an anonymous function you just return it to something.
And being an annonymous function it does not create any scope or naming issues and it can access everything according to where it is defined. So you can call outer function too from inside.