Reputation: 53
hey i'm relativly new to jquery and i've a simple question. I have these two selections and functions, they work fine, but i'm sure it could be written better. How do i combine these two tasks in one?
$('li').attr('data-li', function(index) {
return index;
});
$('nav div').attr('data-div', function(index) {
return index;
});
I've two different selectors, but a nearly identical method, but the problem is that the .attr method has a different argument otherwise i would have written a variable like this.
var ind = $(this).attr('', function(index) {
return index;
}
Upvotes: 0
Views: 34
Reputation: 37137
Create a function and pass it as callback, this is plain js. In javascript you can declare functions and pass them around. The code would look something like this:
function getIndex(index) { return index }
$('li').attr('data-li', getIndex);
$('nav div').attr('data-div', getIndex);
Upvotes: 2