是否可以使用jQuery设置“ for”(AssociatedControlID)属性?我正在尝试像这样将其设置为出现在label之后的下一个控件:
@H_301_6@$('label.asssociateClass').each(function() { var toAssociate = $(this).next(':input'); $(this).attr("for",toAssociate.attr("id")); });
问题是,如果我不通过AssociatedControlID在服务器上设置它,它将永远不会到达这里,因为在这种情况下,它是作为跨度而不是标签呈现的.有没有办法克服这个问题,或者我必须在服务器上做到这一点?
最佳答案
您可以使用
.replaceWith()
使用标签替换范围,如下所示:
@H_301_6@$('span.asssociateClass').each(function() { var l = $("<label class='associateClass' />") .html($(this).html()) .attr('for',$(this).next(":input").attr("id")); $(this).replaceWith(l); });
这是它工作的一个简单示例:http://jsfiddle.net/V73WL/