Jquery auto return value

in this code, what does the function return? and this value is assigned to the id attribute of each div. I found that it returns div-id0 for the first div, div-id1 for the second div.why is this happening?

$("div").attr("id", function (arr) {
  return "div-id" + arr;
})
+3
source share
3 answers

If you provide a function as the second argument attr, the function is executed once for each element in the selection, and the return value is set as the attribute value of that element.

The position in the selection is passed as the first argument to the callback; the current attribute value is passed as the second argument.

$("div").attr("id", function (arr) {
  return "div-id" + arr;
})

, id div div-id . , div-id0, div-id1 ..

index, arr.

+3

. http://api.jquery.com/attr/

.attr( attributeName, function(index, attr) )

attributeName .

function(index, attr) , . . .

+2

When passing a function to attror cssin jQuery, the first parameter passed to the function is the current index of the array , and the second parameter is the current value of the property that you are trying to set for the current element .

+2
source

All Articles