我正在尝试为已经附加了Class的DIV分配ID.这是我的代码: (该类是“myclass”,id是“myid”) $(document).ready(function(){$(".myclass").id("myid"); }); 提前致谢. 如果您使用jQuery 1.6或 .attr() ,请尝试使用
(该类是“myclass”,id是“myid”)
$(document).ready(function(){
$(".myclass").id("myid");
});
提前致谢.
如果您使用jQuery 1.6或.attr(),请尝试使用
.prop():
$(".myclass").prop("id", "myid");
如果你有这个类的多个元素,它将为多个元素分配相同的ID,这是非常糟糕的做法..在这种情况下附加索引:
$(".myclass").each(function(index) {
$(this).prop("id", "myid" + index);
});
编辑:
最优雅和有效的方法是直接使用.prop()或.attr()(在1.6之前)而不使用.each()然后分配直接DOM元素的id:
$(".myclass").prop("id", function(index) {
return "myid" + index;
});
Live test case.
