Changing td's html in JQuery
I want to change text in table td from 1,1,1 to 1,2,3 with jQuery
But it not seem to work. what is wrong in my code?This is my JavaScript function.
function reorder(targetId){
var i = 1;
jQuery.find(targetId).each(function(){
jQuery(this).attr("innerHTML", i);
i ++;
});
}
My html co开发者_Python百科de.
<form>
<input type="button" onClick="reorder('#index');" value="test"/>
<table>
<tr><td id="index">1</td></tr>
<tr><td id="index">1</td></tr>
<tr><td id="index">1</td></tr>
</table>
</form>
You've got a bit of mixed up stuff there. Try this...
function reorder(selector){
jQuery(selector)
.find('tr td:first-child')
// Remove the + 1 if you want it to start at 0.
.html(function(i) { return i + 1; });
}
Here are some of the changes...
- Changed your argument variable to be clearer.
- You can use jQuery('selector'), not
jQuery.find()
. - You can use the
html()
method.
It's worth mentioning too that if you're not using another jQuery library (or don't intend to), you can use $
which is shorter than jQuery
.
I've also modified your HTML
<form>
<input type="button" onclick="reorder('#my-table');" value="test"/>
<table id="my-table">
<tr><td>1</td></tr>
<tr><td>1</td></tr>
<tr><td>1</td></tr>
</table>
</form>
You may have forgot that using multiple id
attributes with the same value is not valid markup. You could use a class there, or better still omit it entirely. You may not care about valid markup, but browsers' CSS and JavaScript could do some funky stuff (now or in the future) when they expect an id
attribute to unique.
I think you need change i values incrementation expression .
function reorder(targetId){
var i = 1;
jQuery.find(targetId).each(function(){
jQuery(this).attr("innerHTML", i);
i++; // Before that it was i ++
});
}
精彩评论