jQuery 检查元素 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10885477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery check element ID
提问by Grigor
I know there is plugin called .hasClass();
我知道有一个插件叫做 .hasClass();
I have the following
我有以下
$('#page_background, #header_background').ColorPicker({...
$('#page_background, #header_background').ColorPicker({...
how would I check if page_background is clicked and not header_background?
我将如何检查是否单击了 page_background 而不是 header_background?
This is what I have now, it won't work.
这就是我现在所拥有的,它不会起作用。
$('#page_background, #header_background').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
var id = this.id;
if(id == 'page_background')
$('body').css("background-color","#"+hex);
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
回答by Prasenjit Kumar Nag
$(function(){
$('#page_background, #header_background').click(function(){
var id = this.id;
if(id == 'page_background')
// page background
else
//header
});
});
As you are using this inside colorpicker onSubmit
function
当您在颜色选择器onSubmit
功能中使用此功能时
onSubmit: function(hsb, hex, rgb, el) {
where you get the element as el
, so to get the id
use
你在哪里得到元素 as el
,所以要id
使用
var id = $(el).attr('id');
// or
var id = $(el).prop('id'); // new way
//or simply
var id = el.id; // this should work too
回答by James Allardice
Assuming you have a reference to the clicked element stored in this
, you can simply use the native DOM property:
假设您有一个对存储在 中的被点击元素的引用this
,您可以简单地使用原生 DOM 属性:
var id = this.id;
If this
is a jQuery object, not a DOM node, you can use this.attr("id")
.
如果this
是 jQuery 对象,而不是 DOM 节点,则可以使用this.attr("id")
.
Also note that hasClass
is a normal jQuery method, not a plugin. It's part of the standard jQuery library.
另请注意,这hasClass
是一个普通的 jQuery 方法,而不是插件。它是标准 jQuery 库的一部分。