【问题标题】:jQuery add empty label tags next to every radio button or checkboxjQuery 在每个单选按钮或复选框旁边添加空标签标签
【发布时间】:2012-01-21 17:53:17
【问题描述】:

我需要一个简单的 jQuery 代码,它会在每个单选按钮或复选框旁边添加一个空标签标签

例如:

$('input[type="radio"]').next().add("<label for="radio"></label>");
$('input[type="checkbox"]').next().add("<label for="checkbox"></label>");

我怎样才能做到这一点?

谢谢。

【问题讨论】:

    标签: jquery input radio-button add next


    【解决方案1】:
    $(':radio, :checkbox').each(function () {
        $(this).before('<label for="' + this.id + '"></label>');
    });
    

    【讨论】:

      【解决方案2】:

      您需要使用after 来完成此操作。此外,您还希望标签的 for 是它所引用的 id

      $('input[type="checkbox"]').each(function() {
           var cb = $(this);
           cb.after($("<label />")
                      .attr("for", cb.attr("id")) );
      });
      

      您说您想要空标签,但以防万一,如果您希望标签显示它们旁边的复选框的值,应该这样做:

      $('input[type="checkbox"]').each(function() {
           var cb = $(this);
           cb.after($("<label />")
                      .attr("for", cb.attr("id"))
                      .text(cb.val()) );
      });
      

      【讨论】:

        【解决方案3】:
        $('input[type="radio"]').after("<label for='radio'></label>");
        $('input[type="checkbox"]').after("<label for='checkbox'></label>");
        

        【讨论】:

          【解决方案4】:

          你想使用jQuery函数.after()

          $('input[type="radio"]').after('<label for="radio"></label>');
          $('input[type="checkbox"]').after('<label for="checkbox"></label>');
          

          但是,如果您希望标签定位到正确的元素,则需要这样做:

          $('input[type="radio"], input[type="checkbox"]').each( function() {
              var id = $(this).attr( "id" );
              $(this).after('<label for="' + id + '"></label>');
          } );
          

          需要将元素的id放在label标签的for属性中

          【讨论】:

          • 需要将双引号改为单引号 ""
          • 它不起作用,它甚至损坏了该页面上的其他 JavaScript。
          • @user1090389 这是jsfiddle 显示它没有问题;)如果它不适合您,那是因为您添加不正确。
          猜你喜欢
          • 1970-01-01
          • 2014-12-01
          • 1970-01-01
          • 2019-02-15
          • 1970-01-01
          • 2012-10-16
          • 1970-01-01
          • 2016-01-13
          • 2013-04-21
          相关资源
          最近更新 更多