Jquery设置标签的属性

时间:2022-11-19 15:21:06

Is it possible to set "for"(AssociatedControlID) attribute using jQuery? I am trying something like this to set it to the very next control that appears after label:

是否可以使用jQuery设置“for”(AssociatedControlID)属性?我正在尝试这样的东西将它设置为标签后出现的下一个控件:

$('label.asssociateClass').each(function()
{

      var toAssociate = $(this).next(':input');

      $(this).attr("for", toAssociate.attr("id"));

});

The problem is that if I don't set it on a server through AssociatedControlID it never gets here since it's rendered as span instead of label in that case. Is there a way to overcome this or I have to do it on a server?

问题是,如果我没有通过AssociatedControlID在服务器上设置它,它永远不会到达这里,因为它在那种情况下被渲染为span而不是label。有没有办法克服这个问题,或者我必须在服务器上做到这一点?

2 个解决方案

#1


2  

You can replace your spans with labels using .replaceWith() like this:

您可以使用.replaceWith()替换标签,如下所示:

$('span.asssociateClass').each(function() {
  var l = $("<label class='associateClass' />")
           .html($(this).html())
           .attr('for', $(this).next(":input").attr("id"));
  $(this).replaceWith(l);
});​

Here's a quick example of it working: http://jsfiddle.net/V73WL/

以下是它工作的一个简单示例:http://jsfiddle.net/V73WL/

#2


0  

you can't change behavior of asp:label, however you can change tag using jquery

你无法改变asp:label的行为,但你可以使用jquery更改标签

$(function () {
    var spans = $('span.label').each(function() {
        input = $(this).next('input');      
        $('<label />').html($(this).html()).attr('for', input.attr('id')).insertBefore(input);
        $(this).remove();
    });
});

#1


2  

You can replace your spans with labels using .replaceWith() like this:

您可以使用.replaceWith()替换标签,如下所示:

$('span.asssociateClass').each(function() {
  var l = $("<label class='associateClass' />")
           .html($(this).html())
           .attr('for', $(this).next(":input").attr("id"));
  $(this).replaceWith(l);
});​

Here's a quick example of it working: http://jsfiddle.net/V73WL/

以下是它工作的一个简单示例:http://jsfiddle.net/V73WL/

#2


0  

you can't change behavior of asp:label, however you can change tag using jquery

你无法改变asp:label的行为,但你可以使用jquery更改标签

$(function () {
    var spans = $('span.label').each(function() {
        input = $(this).next('input');      
        $('<label />').html($(this).html()).attr('for', input.attr('id')).insertBefore(input);
        $(this).remove();
    });
});

相关文章