【问题标题】:I need to loop through all input elements [closed]我需要遍历所有输入元素[关闭]
【发布时间】:2014-01-23 14:20:15
【问题描述】:

我正在尝试遍历 div 元素内的所有动态创建的输入。第一个输入元素已经存在于 dom 中。

我使用了以下代码:

$(document).on("click", "#myClickLink",function(){
   $("#divElement input").each(function(){ 
      alert($(this).val()); 
   });  
});

问题是我只得到第一个输入元素,有什么帮助吗?

提前致谢

【问题讨论】:

  • 也向我们展示您的HTML,或在Fiddle 上点赞online demo
  • input[type=text] 试试这个吧..
  • 我的问题出在我的动态生成输入中,我被追加到另一个 div... 非常感谢您的帮助

标签: jquery loops dynamic input each


【解决方案1】:

您的代码在包装在 jquery 就绪函数中时可以工作。

$(document).ready(function() {
    $(document).on("click", "#myClickLink",function(){
        $("#divElement input").each(function(){ 
            alert($(this).val()); 
        });  
    });
});

【讨论】:

  • 不知道他的html标记怎么知道?
  • 他是only getting the first input element,所以他的代码正在运行
  • 我使用他在代码中提供的所有元素,用我自己的代码对其进行了测试。
  • 我的问题已经解决了,谢谢你的帮助。
【解决方案2】:

在我看来你应该append()input element first, 然后只有你可以在$.each loop 中获得newly created input elements 喜欢,

$(document).on("click", "#myClickLink",function(){
   newid=$("#divElement input").length+1;
   // append a new input first
   $("#divElement").append('<input type="text" id="'+newid+'" value ="'+newid+'" />');
   $("#divElement input").each(function(){ 
      alert($(this).val()); 
   });  
});

DemoDemo with add more and check links

【讨论】:

  • 谢谢,你的回答帮我找到了错误,我使用 appendTo 并指向另一个 div
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多