【问题标题】:How to find the connection between a radio button and a label?如何找到单选按钮和标签之间的联系?
【发布时间】:2012-02-24 01:16:23
【问题描述】:

我有这个标签:

<label id="options_31409_3label" for="options_31409_3"><span>some text</span></label>

如您所见,跨度内的标签中有一些文本。现在我还有一个单选按钮,位于标签的左侧:

<input id="options_31409_3" class="radio" type="radio" value="72058" name="options[31409]" onclick="xyz()">...</input>

这是一个单选和一个标签,但我在同一个站点上有几个单选按钮和标签。现在从这 N 个标签和单选按钮中,我必须识别一对并用它做一些原型的东西。每次加载站点时,该对都有不同的 id,唯一保留的是跨度内的文本。如果跨度内有“一些文本”,有没有办法获取标签和单选按钮?如果有帮助,我可以使用 Prototype。

谢谢!

【问题讨论】:

    标签: html prototypejs radio-button label


    【解决方案1】:

    因为您知道标签的 id 由输入的 id + 'label' 组成,所以您可以使用例如下面的代码找到一对:

    $$('input[type=radio]').each(function() 
        var input = this;
        var label = $(this.id + 'label');
        // do something for input and label
    });
    

    【讨论】:

      【解决方案2】:

      labels for 属性如果使用正确,应该与inputs id 属性具有相同的值。因此,您可以像这样轻松找出哪个label 属于哪个input

      $$('label').each(function () {
          var label = this;
          var input = document.getElementById(label.getAttribute('for'));
      });
      

      【讨论】:

        【解决方案3】:

        我会选择改进 jholser 的 sn-p 以适用于所有标签,而不仅仅是那些 ID 中有“标签”的标签。

        $$('input[type=radio]').each(function(input) 
        {
            // Several labels may link to the same input
            $$('label[for="' + input.identify() + '"]').each(function(label)
            {
                // do something for input and label
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-25
          • 1970-01-01
          相关资源
          最近更新 更多