jQuery index on each function
I am curious why I need this index
$(document).ready(function() {
$(".divToggle").each(function(index){
var buttonId = $(this)[0].attributes["id"].value.toString();
var idParts = buttonId.split('_');
var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
$(this).click(function() {
$("#" + uniquePart).toggle("slow");
});
});
});
Why do I need the "[0]" in "var buttonId =开发者_C百科 $(this)[0]…" Without it, I get an attributes["id"] is null error..
Use this instead
var buttonId = this.id;
or jQuery way
var buttonId = $(this).attr("id");
with $(this) you are still in the jquery model where the correct way to get id is .attr("id")
writing $(this)[0] drops you back into the DOM model where its as you wrote.
$(this)[0]
Is doing 2 things -
- Getting you the first element in the matched set, as you're looping round a set of results one by one the index is probably redundant in this case
- Returning a 'normal' JavaScript DOM object rather than a jQuery wrapped object
Looking at your code I believe you could achieve the same result by doing this -
var buttonId = this.id;
$(".divToggle").each(function(index, element){
var buttonId = element.id,
idParts = buttonId.split('_'),
uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
$(element).click(function() {
$("#" + uniquePart).toggle("slow");
});
});
try
var buttonId = $(this).attr("id");
Technically you don't need it with a little modification of your code. What happens with jQuery selectors is they are simply a bunch of element references in an array. so instead of
<div id ="myelement"></div>
you get
[<div id ="myelement"></div>]
using $(this)
puts this
in an array and allows it to be used with jQuery functions. If you aren't using jQuery functions just use this
. So your code would become
var buttonId = this.attributes["id"].value.toString();
精彩评论