得到jquery`$(this)`id [英] get jquery `$(this)` id

查看:768
本文介绍了得到jquery`$(this)`id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得触发jQuery .change()函数的元素的 id
函数本身正常工作,但我需要一个具有 id =next的选择器的特定动作。


$ b $ ($($))
$> $($$ c $)$(select)。change(function(){
[... snip ....]
alert .attr('id')); //< ----不工作
}

任何想法为什么上述警报不起作用? $ c>是事件挂钩的DOM元素, this.id 是它的ID,不需要将它包装在jQuery实例中以获取它,<$

  $(select)这个属性可以在所有浏览器中可靠地反映属性。 ).change(function(){
alert(Changed:+ this.id);
}

现场示例



你没有做这在你的代码示例中,但是如果你正在看一个带有多个表单元素的容器,那会给你的容器的ID r 。如果你想要触发事件的元素的ID,你可以从 事件对象的 目标属性:

 $(#container)。change(function(event){
alert(Field+ event.target.id +changed);
});

现场示例



(jQuery确保更改事件泡泡,即使在IE本身不会执行的情况下也是如此。 )

How can I get the id of the element that triggered the jQuery .change() function? The function itself works properly, but I need a specific action for a selector with id="next".

$("select").change(function() {
    [...snip....]
    alert( $(this).attr('id') );  // <---- not working
}

Any ideas why the alert above isn't working?

解决方案

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

这篇关于得到jquery`$(this)`id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆