无法使用 event.target.id 获取触发事件的输入 ID

unable to get the input id that triggered the event using event.target.id

我这里有这段代码,用于获取单击的输入元素的 ID:

jQuery(event.target.id).change(function(){

if(event.target.id===null)
    {

    }
else
    {   
    alert(event.target.id);
    }
});

例如:我有一个动态生成的文本框。使用上面的代码单击它后,它 returns id。

然而,当我单击下拉列表输入时,它 returns 为空,但在检查元素时,id 在那里。它仍然转到 else 块。

我将此事件用于动态生成的字段。

可能出了什么问题?

抱歉,我是 jQuery 的新手。

在 select 元素上你需要监听更改事件,而不是点击事件:

$('select').change(function() {
  var selectId = $(this).attr('id');
  var optionId = $(this).find(":selected").attr('id');
  alert('select id:' + selectId);
  alert('option id: ' + optionId);
});

更新 通常在 select 元素中,您会查找选项值。您可以这样做:

$('#selectId').change(function() {
  var optionValue = $(this).find(":selected").val()
  alert(optionValue);
});

尝试访问原始目标

 var originalElement = event.srcElement || event.originalTarget;
 console.log(originalElement.id)