【问题标题】:Get value from input tags in JS with no id or HTML control从没有 id 或 HTML 控件的 JS 中的输入标签中获取值
【发布时间】:2015-12-11 07:50:32
【问题描述】:

本项目中的 HTML 由解析系统生成。所以我无法控制 HTML。但是我可以添加 javascript 或 jquery。

HTML 看起来像这样:

<div class="input-group" id="userList">
  <span ../>
  <ul class="accepted-suggestions">
     <li><div class="user">...</div>
         <input type="hidden" value="myUserName1"></input>
     </li>
     <li><div class="user">...</div>
         <input type="hidden" value="myUserName1"></input>
     </li>
     <li as many list elements as the user is selecting>
      .......
     </li>
  </ul>  
</div>

在 HTML 中,当登录用户选择要添加到列表中的用户时,会填充 ul 列表。如何访问在 jquery 的此列表中添加的隐藏输入值?请注意,我无法向 HTML 添加任何内容。

【问题讨论】:

  • 当您知道确切的文档结构时,您可以浏览 DOM 树。使用 document.getElementsByClassName('accepted-suggestions') 函数获取您的 &lt;ul&gt; 标签,然后从那里导航到相应的 childNodes 以获取您的输入。

标签: javascript jquery html input


【解决方案1】:

由于您没有提到访问后如何处理它们

 $( ".accepted-suggestions" ).find( "li input[type='hidden']" ).each( function(){

    alert( $(this).val() );

    });

【讨论】:

  • 该死的,打败我。写的几乎一模一样:D
【解决方案2】:

我在示例中使用了您的代码:

工作JSFIDDE

这里是html代码:

<div class="input-group" id="userList">
  <span ../>
  <ul class="accepted-suggestions">
     <li><div class="user">...</div>
         <input type="hidden" value="myUserName1">
     </li>
     <li><div class="user">...</div>
         <input type="hidden" value="myUserName1">
     </li>
     <li as many list elements as the user is selecting>
      .......
     </li>
  </ul>  
</div>

jquery 代码:

var li_objs = $('ul.accepted-suggestions').find('li');
var input_objs = $('ul.accepted-suggestions').find('input');
alert(li_objs.length);

alert(input_objs.length);

input_objs.each(function (i,input_obj) {
    alert($(input_obj).attr('value'));
})

【讨论】:

    【解决方案3】:

    它有名称值吗?你可以使用:

    onclick="execute(document.getElementsByName('textbox1')[0].value)
    

    var inputs, index; inputs = document.getElementsByTagName('input'); 
    for (index = 0; index < inputs.length; ++index) {
    
    // deal with inputs[index] element.}
    

    【讨论】:

      【解决方案4】:

      在 JavaScript 中 检查 document.getElementsByTagName("input") 的 type 属性,看看它是否被隐藏。 所以:

      var x = document.getElementsByTagName("input");
      //loop for all the x values
      for(var i=0;i<=x.length;i++){
      var type=x[i].type // see if it is hidden.
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-02
        • 1970-01-01
        • 2019-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-27
        • 1970-01-01
        相关资源
        最近更新 更多