我在页面中动态加载三个文本框,我需要在单击文本框时获取文本框的 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 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/