简体   繁体   English

无法获取动态创建的元素的ID

[英]Cannot get id of dynamically created element

I'm making a webpage that will dynamically generate a number of inputs via ajax. 我正在制作一个网页,它将通过ajax动态生成大量输入。 I would like to retrieve the id (and ultimatly the new value) of any input that is changed. 我想检索已更改的任何输入的ID(最后是新值)。 Below is a very simple example of my site. 以下是我网站的一个非常简单的示例。 Right now I'm using delegate to attach an event handler to retrieve the id and new value of the input, but I cannot get the values I want. 现在,我正在使用委托来附加事件处理程序,以检索输入的ID和新值,但是我无法获取所需的值。 Is my implementation incorrect? 我的实现不正确吗? I'm new to jquery so any help would be appreciated. 我是jquery新手,所以将不胜感激。 Thanks. 谢谢。

<html>
  <head>
  </head>
  <body>
    <div class="container">

      <form id="test_form">
            <input type="submit">
      </form>

      <div id="inputs">
      </div>
    </div>

    <script src="../static/js/jquery-1.11.0.min.js"></script>
    <script src="../static/js/loader.min.js"></script>
    <script>


    $("#test_form").submit(function() {
        // this variable is just an example, the actual variable will be
        // returned via ajax and will have 1-20 inputs
        var inputs = {
            input1: "default1",
            input2: "default2"
        }

        for (var key in inputs) {
            var li = $("<li>")
            var input = $("<input>")
            input.attr({
                type: "text",
                value: inputs[key],
                id: "id_" + key
            })
            li.append(input)
            $("#inputs").append(li)
            input.onchange
        }

        return false; // stop the form from submitting
    });

    var onChangeFunction = function(){
       // does not show id of the input the text was changed on
       alert($(this).id)
       alert($(this).value)
    }

    $("#inputs").delegate("input", "change", onChangeFunction)


    </script>
  </body>
</html>

jQuery objects do not have an id property or value property. jQuery对象没有id属性或value属性。 You need to use .attr() to get the DOM attributes of the elements like id (or sometimes .prop() ), and you can use .val() to read the value property: 您需要使用.attr()来获取id (或有时是.prop() )等元素的DOM属性,并且可以使用.val()来读取value属性:

alert($(this).attr("id"))
alert($(this).val())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM