繁体   English   中英

获取动态创建的元素jQuery的id

[英]Getting id of dynamically created element jQuery

我正在使用下拉列表生成一些输入字段。 我现在希望输入到这些输入字段的文本能够自动更新范围。 但是,由于输入字段是动态生成的,因此我很难使用jQuery

谢谢你的帮助!

HTML:

<div id="url">
    https://api.test.com<span id="endpoint" readonly="readonly"> </span>
</url>

<div class="control-group">
    <label class="control-label" for="selectbasic">Endpoint</label>
    <div class="controls">
        <select id="dropdown" name="selectbasic" class="input-xlarge">
        <option value = "none">select</option>
            <option value="id">/test/{id}</option>
            <option value="id_date">/test/{id}/{date}</option>
        </select>
    </div>

JavaScript的:

$('#dropdown').change(function(){
    $('#textBoxContainer').empty();
    var data = $(this).find('option:selected').attr('value');
    var cleaned_data = data.split("_");
    var num_args = cleaned_data.length;
    for (var i = 0; i < num_args; i++){
        $('#textBoxContainer').append('<label class="control-label" for="textinput">' + cleaned_data[i] + '</label><br/><input id="' + cleaned_data[i] + '" name="textinput" size="25" type="text" placeholder="'+ cleaned_data[i] +'" class="input-xlarge"><br/>');
    }

});

jQuery('#date').on('input', function() {
    $('#endpoint').html('test');
})

这是小提琴

现场演示

$("#textBoxContainer").on('input','#date', function () {
    $('#endpoint').html(this.value);
});

阅读有关动态生成元素.on()方法和事件委托的文档

您可以创建元素并同时分配函数

DEMO

        $('#textBoxContainer').append( 
            $("<input/>", 
              {
                type: "text", id: cleaned_data[i],
                name: "textinput", size:25, 
                placeholder: cleaned_data[i], 
                class:"input-xlarge", 
                keyup: function inputkeyup(){
                    $("#endpoint").text(this.value);
                }
            })
        ).append("<br/>");

这是你更新的jsfiddle jsfiddle.net/pgHvV/7/

在你的for循环中做所有事情......你可以创建和操作并利用控件及其内部的值......

检查一下

for (var i = 0; i < num_args; i++){ $('#textBoxContainer').append('<label class="control-label" for="textinput">' + cleaned_data[i] + '</label><br/><input id="' + cleaned_data[i] + '" name="textinput" size="25" type="text" placeholder="'+ cleaned_data[i] +'" class="input-xlarge"><br/>'); /*do everything here.. you can create a on click on onchange or onblur or on anything for that id....*/ }

暂无
暂无

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

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