jQuery onClick捕获元素的id

jQuery onClick捕获元素的id,jquery,jquery-selectors,Jquery,Jquery Selectors,我有很多这样的输入字段 <input type="radio" name="name" id="name" onchange="enableTxt()" /> 我得到这个错误 a.attributes is undefined HTML: 将此消息传递给函数 enableTxt(this) function enableTxt(item) { var id = $(item).attr("id"); alert(id); } 试试这个 alert($("in

我有很多这样的输入字段

<input type="radio" name="name" id="name" onchange="enableTxt()" /> 
我得到这个错误

a.attributes is undefined
HTML:


将此消息传递给函数

enableTxt(this)

function enableTxt(item) {
    var id = $(item).attr("id");
    alert(id);
}
试试这个

alert($("input:radio").attr('id'));

您可以只传递HTML中的ID

<input type="radio" name="name" id="name" onchange="enableTxt($(this).attr('id'))" />

function enableTxt(id)
{
    alert(id);
}

函数enableTxt(id)
{
警报(id);
}

另一个选项是JQ

$("#name").on('onchange',enableText);
有了它,您的对象将成为当前html

 <button class="destroy" id="123">

此视频可能有帮助:-

我尝试使用
$(this.attr(id)

但是返回了一个
未定义的错误

但使用这种方法(在视频中)奏效了

我的用例:
自动生成的列表项“

函数打印(listItem){console.log(listItem.id)}

它输出单击的
元素的id

Harsha,您需要将其作为参数传递给函数,即issue@harsa一个建议是,由于您已经在使用jquery,请将内联函数更改为document.ready onchange事件,这样就可以清晰地分隔,并且减少诸如传递值等错误的更改汉克斯州长:我想你是对的,你在几秒钟内就击败了我的答案,嗯,开玩笑吧。我喜欢你的回答,它是最干净的。我不明白的一件事是
e.preventDefault()
您添加的行。您能解释一下为什么会有这样的行吗?如果按钮位于表单中,这将阻止表单发布,这样它将保持在同一页上。您的问题中不需要它,可以忽略它
<input type="radio" name="name" id="name" onchange="enableTxt($(this).attr('id'))" />

function enableTxt(id)
{
    alert(id);
}
$("#name").on('onchange',enableText);
 <button class="destroy" id="123">
  $('button.destroy').on('click', function(e){
    e.preventDefault();
    console.log(this.id);