Jquery获取最近一次单击的属性ID

Jquery get attribute ID for latest click

本文关键字:单击 一次 属性 ID 获取 最近 Jquery      更新时间:2023-09-26

im试图通过jquery 获取属性值

$(document).click(function() {                                    
            var elem = $("input[name='phone']");
            alert(elem.length);
            if(elem.length > 0){
                  alert(elem.attr('id'));
                }
            }); 

这里是

我有很多不同形式的与"phone"同名的输入字段。每当我点击它时,我只能得到第一个值。不是最后一个。我如何通过Jquery获取它。

在我的页面中,只有文档点击才能工作,因为表单代码是从其他网站加载的。

任何帮助都将更加感谢

 $( "input[name^='phone']" ).last()

将返回名称以"phone"开头的最后一个元素

您可以这样做,以获取所单击项目的id。

$("input[name='phone']").click(function() {      
    alert($(this).attr('id'));
}

这是将侦听器附加到电话输入,this是上下文,在本例中是单击的项目。

试试这个:

$("input[name='phone']").on('focus', function(){
    alert($(this).attr('id'));
}

这将监听您的phone输入字段上的点击,并提醒您在屏幕上看到id属性:

JQuery

$("input[name='phone']").click(function() {                                    
    alert($(this).attr("id"));
});

HTML示例

<input id="a" name="phone">A</input>
<input id="b" name="phone">B</input>
<input id="c" name="phone">C</input>
<input id="d" name="phone">D</input>

使用.on()委派事件,然后可以使用this:

$(document).on('click', 'input[name="phone"]', function() {
  console.log('element with id: ' + this.id + ' has value: ' + this.value);
});