【问题标题】:Retrieve Field properties in JQuery检索 JQuery 中的字段属性
【发布时间】:2009-06-29 06:56:27
【问题描述】:

我是 JQuery 的新手。

我在一个 DIV 中创建了许多文本字段、文本区域字段。在该 div 中,我有序地为每个字段(包括标签标签和字段(text/textarea))保留了单独的 div。

现在我正在尝试在单击保存时检索标签名称和这些字段的类型、大小。我如何在 JQuery 中这样做?

另外,我可能不知道该标签后面有哪些字段。它可能是任何文本,文本区域等。是否可以找到标签标签后面的标签??

这里是html:

    <div id="fb_contentarea_col1down21">

    <div id="1">
               <label id="label1">name</label>
              <input type="text" style="width: 200px;" id="input1"/><br/>
               <div id="instr1"/>
           </div>
            <div id="2">
              <label id="label2">address</label>
              <textarea id="input2" style="width: 200px;"/><br/>
              <div id="instr2"/>
          </div>

        </div><!-- End of fb_contentarea_col1down21 -->

<div id="save"><input type="submit" value="Save Form" class="button" id="saveForm"/>

【问题讨论】:

    标签: jquery


    【解决方案1】:
    $('#1 label').text(); // gets label contents: "name"
    
    var input1 = $('#1 label').next(); // gets input1
    input1.width(); // input1's width: 200
    input1.attr('type'); // input1's type: "text"
    input1[0].tagName; // input1's tag type: "input" ([0] gets the dom element)
    
    $('#2 label').next()[0].tagName; // input2's tag type: "textarea"
    

    【讨论】:

      【解决方案2】:

      (延伸到桑德萨的回答)

      如果您对标签使用“for”属性,那么您可以去掉包装器 div 上的 id,或者如果其唯一目的是帮助识别相关标签,则可以去掉整个包装器 div。

        <label for="input1">name</label>
        <input type="text" style="width: 200px;" id="input1"/><br/>
         <div id="instr1"/>
        <label for="input2">address</label>
        <textarea id="input2" style="width: 200px;"/><br/>
        <div id="instr2"/>
      

      然后你就可以写了,

      $('#save').click( function () {
          $.each(['input1', 'input2'], function (idx, selector) {
              var label = $('label[for=' + selector + ']');
              var input = $('#' + selector);
      
              alert(label.text());       // label name
              alert(input.width());      // input width
              alert(input[0].tagName);   // tagname
              alert(input.attr('type')); // type attribute
          });
      });
      

      【讨论】:

        【解决方案3】:

        除了在单击按钮时执行操作的 sandersa 答案之外,您还可以执行以下操作:

        $("#saveForm").click(function() {
          // Borrowing code from sandersa's answer
          alert($('#2 label').next()[0].tagName);
        });
        

        【讨论】:

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