我有一个元素:
<select id="row" />
我想将一个字符串附加到 id 属性的末尾,如下所示:
<select id="row_1" />
我用来实现此目的的 jQuery 是(在 each
中):
$(this).attr('id',$(this).attr('id')+'_'+row_count);
这看起来很丑陋,虽然它有效,但我想知道是否有更简单的解决方案。在此示例中,ID 前缀(例如行)永远不是恒定的,因此我不能只执行 'row_'+row_count
。
干杯!
最佳答案
不要忘记扩展 jQuery 非常简单:
$.fn.appendAttr = function(attrName, suffix) {
this.attr(attrName, function(i, val) {
return val + suffix;
});
return this;
};
然后在您想要执行此操作的其他地方:
$('p').appendAttr('id', 'i_like_turtles');
关于jquery - 使用 jQuery 将字符串附加到元素属性的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2516075/