最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The shortest way of modifying attributes in jQuery - Stack Overflow

programmeradmin4浏览0评论

I am doing this:

$("td.myTD").each( function(){
    var rowspan = $(this).attr("rowspan");
    rowspan = parseInt(rowspan) + 1;
    $(this).attr("rowspan", rowspan);                            
});

(incrementing by one the rowspan for all the td with class myTD). Is there a shorter way of writing it?

In a perfect world I would like to write soemething like this:

$("td.myTD").attr("rowspan", someMagicHereToGetTheAttrValueForEachFoundElement() + 1);

Is it possible?

I am doing this:

$("td.myTD").each( function(){
    var rowspan = $(this).attr("rowspan");
    rowspan = parseInt(rowspan) + 1;
    $(this).attr("rowspan", rowspan);                            
});

(incrementing by one the rowspan for all the td with class myTD). Is there a shorter way of writing it?

In a perfect world I would like to write soemething like this:

$("td.myTD").attr("rowspan", someMagicHereToGetTheAttrValueForEachFoundElement() + 1);

Is it possible?

Share Improve this question asked Jul 5, 2013 at 13:40 PaoloPaolo 2,4726 gold badges34 silver badges45 bronze badges 1
  • The .attr() method does support a way to do what you are asking, as shown in the answers below, but note that even if it didn't you could shorten the code by eliminating the rowspan variable and using the unary plus operator instead of parseInt(): $(this).attr("rowspan", +$(this).attr("rowspan") + 1) - of course, you'd still need the .each() that way. – nnnnnn Commented Jul 5, 2013 at 13:52
Add a ment  | 

2 Answers 2

Reset to default 14

You can do this using the .attr( attributeName, function(index, attr) ):

$("td.myTD").attr("rowspan", function(index, attr){
    return parseInt(attr, 10) + 1;
});

Here, the above code uses a function which takes the index position of the element in the set and the old attribute value as arguments. And then the function returns a new attribute value based on the old attribute. This use of a function to pute attribute values is particularly useful when modifying the attributes of multiple elements at once.

For more information, see the attr function(index, attr) documentation.

.attr() can take a function that returns the new value from the old one:

$("td.myTD").attr("rowspan", function(i, old) { return +old+1 });

DOCUMENTATION

发布评论

评论列表(0)

  1. 暂无评论