【问题标题】:get val() from dynamically generated text element从动态生成的文本元素中获取 value()
【发布时间】:2016-09-18 02:10:15
【问题描述】:

好的,所以我有一些动态生成的文本框,当我调用 .val() 时找不到它们的值。在页面加载时呈现的文本输入将返回一个带有 .val() 的值,但其余的都不会。

如果此示例不足以得到答案,那么我将使用我的实际代码编辑问题,但我已尽力准确地简化它。

JQuery:

numBoxes = 0

function newText(){
  numBoxes++
  $('<div id="' + numBoxes + '"><input id="soft_text_' + numBoxes + 
    '" type="text"></div>').insertBefore($('button#new'))
}

function logHard(){
  console.log($('input#hard_text').val())
}

function logSoft(){
  $('div').each(function(){
    console.log($('input#soft_text_' + this.id).val())
  })
}

HTML:

<html><body>
<input id="hard_text" type="text" name="first_text">
<button id="new" onclick="newText()">Add new text box</button>
<button onclick="logHard()">Log first text box</button>
<button onclick="logSoft()">Log new text boxes</button>
</body></html>

【问题讨论】:

  • 可能是因为里面没有文字?
  • “我已尽力准确地简化它。” 简化很好,但应该是minimal reproducible example。在这种情况下,由于它是基于浏览器的技术,因此请使用 Stack Snippets(&lt;&gt; 工具栏按钮)使其成为 可运行 MCVE。
  • 可能这就是你需要的Please check this link
  • 你真的尝试过你的代码吗?它工作正常:jsfiddle.net/kfssqg0c(如果您的实际代码不起作用,则不代表您的实际代码)
  • "..动态生成的文本框..." "..在加载时呈现的将返回..rest 不会.." 听起来像是将事件绑定到元素的常见问题还不存在:stackoverflow.com/questions/203198/…

标签: jquery html


【解决方案1】:

这就是我解决问题的方法。 @Niet,您建议使用更好的选择器会有所帮助。将来我会努力使用不需要顺序识别的选择器,但这会让它在今天发挥作用。

function logSoft(){
  $('div').each(function(){
    console.log($('div#' + this.id + ' > input').val())
  })
}

【讨论】:

    【解决方案2】:

    你应该改进你的选择器。保持递增的 ID 通常表明您做错了。

    比如……

    function newText(){
      $('<div class="addedbox"><input type="text"></div>').insertBefore($('button#new'));
    }
    function logHard(){
      console.log($('input#hard_text').val());
    }
    function logSoft(){
      $('div.addedbox>input').each(function(){
        console.log($(this).val());
      })
    }
    

    【讨论】:

    • 谁说这解决了 OPs 问题?这可能是一个(长)评论。
    • 虽然我同意 ID 有点狡猾,但这不太可能解决实际问题。
    • 感谢您向我提示“>”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多