javascript - 如何获取动态加载的文本框的id -jquery

标签 javascript jquery

我在页面中动态加载三个文本框,我需要在单击文本框时获取文本框的 id。

$.ajax({
    url: "../taxClass/getTaxClass",
    type: "post",
    contentType: "application/json",
    dataType: "json",
    success: function (data) {
        var taxClassBOs = data.taxClassBOs;
        $.each(taxClassBOs, function (key, value) {
            $("#taxVatId").append('<div><label class="col-sm-3 control-label" for="VatId">' + value.description + '</label></div><div class="col-sm-3"><input type="text" name="vatId" value=""placeholder="' + value.title + '" id="' + value.taxClassId + '" class="form-control" /></div>');
        });
    }
});

我已经尝试过这段代码

$('input[type="text"]').click(function () {
    var id = $(this).attr('id');
    alert(id);
});

最佳答案

您需要event delegation将事件与动态添加的元素绑定(bind)。您可以使用on()为此。

$('staticParent').on('click','input[type="text"]'function(){

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

关于javascript - 如何获取动态加载的文本框的id -jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30530130/

相关文章:

javascript - 在 JSDoc 中,如何将参数类型作为来自对象字符串属性常量数组的字符串应用?

javascript - 从数组中删除匹配的对象,同时将其添加到另一个数组

javascript - 将 React PureComponent 重构为基于钩子(Hook)的功能组件

javascript - IE11 和 Chrome 中的点击事件传播不同?

javascript - 如何动态选择 previous sibling 元素

javascript - 如何使用 ng-repeat 和 filter 获取 JSON 数据

jquery - Bootstrap 4 navbar collapse .show class delay after .collapsing disable

jquery - 在 CSS/JQuery 中制作蒙版画廊

jquery - 使用数据字段存储 JSON?

jquery - 如何使用 JQuery 将某个项目后的 <ul> 一分为二?