gibberish gibberish - 7 months ago 9
Javascript Question

jQuery underscore as first arg of function

I have the following code snippet:

MARKUP:

<tr name="tr3" id="tr3">
<td>
<input type="text" class="common_cls" name="dt[]" id="dt1">
</td>
<td>
<input type="hidden" name="fn[]" id="fn1">
<span id="sp1"><a href="#" id="ah1">choose file</a><span>
<input type="file" name="fff[]" id="ff">
<input type="text" style="display:none">
</td>
</tr>';


JAVASCRIPT

$(document).on('click', '#add_row', function() {
var row = $("table#DocTable tr:eq(3)");
row.clone(true)
.show()
.find("a, input, span").each(function() {
$(this)
.val('')
.attr('id', function(_, id) {
var newcnt = id + count;
return id + count;
});
})
.end()
.appendTo("table");
count++;


I wrote this over a year ago and I had assistance with the bit in question.

What is the purpose of the underscore as the first argument of the function called in the .attr method?

How exactly does that function work? Does it just replace the current
id
in all
a
,
span
and
input
tags with an incremented number?

Answer

The index of the current element is stored in the _ in this case. All that function does is update the attribute of each element with that element's id + count. If you instead named it index or i you may have been able to guess that it contained the index..

Comments