开发者

Append a string to the end of an element attribute using jQuery

I have an element:

<select id="row" />

I want to append a string to the end of the id attribute, like this:

<select id="row_1" />

The jQuery I am using to achieve this is (f开发者_JAVA技巧rom within an each):

$(this).attr('id',$(this).attr('id')+'_'+row_count);

This looks ugly as sin, and whilst it works I want to know if there is a simpler solution. In this example, the ID prefix (e.g. row) is never constant, so I can't just do 'row_'+row_count.

Cheers!


Don't forget that extending jQuery is super easy:

$.fn.appendAttr = function(attrName, suffix) {
    this.attr(attrName, function(i, val) {
        return val + suffix;
    });
    return this;
};

And then everywhere else you want to do this:

$('p').appendAttr('id', 'i_like_turtles');


You can pass .attr() a function, like this:

$("select").attr("id", function(i, val) {
  return val + '_' + i; //i == index, val == original attribute, the id
});

Scroll down a bit here to find the function overload for .attr()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜