jQuery 点击事件获取元素的 id

38

我有许多类似这样的输入字段

<input type="radio" name="name" id="name" onchange="enableTxt()" /> 

当我点击这个单选按钮时,我想要获取单选输入框的id。我正在使用以下代码:

function enableTxt() {
    var id = $(this).attr("id");
    alert(id);
}

我遇到了这个错误

a.attributes is undefined

1
Harsha,你需要将这个作为参数传递给函数,这就是问题所在。 - kobe
1
@harsa,我有一个建议,既然你已经在使用jQuery,那么将内联函数更改为document.ready onchange事件,这样就会有清晰的分离和更少的错误机会,例如传递值等。 - kobe
谢谢,我认为你是正确的。 - Harsha M V
8个回答

70

HTML:

<input type="radio" name="name" id="name" onchange="enableTxt(this)" /> 

JS:

function enableTxt(elem) {
    var id = $(elem).attr("id");
    alert(id);
}

1
你在几秒钟内就超过了我的答案,哈哈,只是开玩笑。 - kobe

10

这是HTML

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

jQuery

  $('button.destroy').on('click', function(e){
    e.preventDefault();
    console.log(this.id);

我喜欢你的回答,它很干净。唯一让我不明白的是你添加的 e.preventDefault(); 这行代码。你能否解释一下为什么要加这个? - Jacob
1
如果按钮在表单中,这将防止表单提交,从而使其保留在同一页上。这不是您问题中必需的,可以忽略。 - Harry Bosh

5
您可以仅从HTML中传递ID。
<input type="radio" name="name" id="name" onchange="enableTxt($(this).attr('id'))" />

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

2
将此传递给函数。
enableTxt(this)

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

2

试试这个

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

1
这个视频可能会有所帮助:- https://youtu.be/gO286Isc5FM 我尝试使用$(this).attr(id),但是会返回一个undefined error。但是使用这个方法(在视频中)可以解决问题。
我的用例: <h1 id = "Autogenerated" Onclick="print(this)">AutoGeneratedlistItems<h1>" function print(listItem){console.log(listItem.id) } 输出了Clicked元素的id。

0

您可以使用jQuery的onclick方法,如下:

$('input[type="radio"]').click((e)=> {
  id = e.target.id;
  console.log('id = ',id);
});
<input type="radio" name="name" id="name" />
<label for="name">Click Me</label>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


0

另一个选项是使用JQ

$("#name").on('onchange',enableText);

使用此方法,您的对象将成为当前的this


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接