jQuery检查元素ID

Gri*_*gor 7 jquery

我知道有一个名为.hasClass()的插件;

我有以下内容

$('#page_background, #header_background').ColorPicker({...

我如何检查是否单击了page_background而不是header_background?

这就是我现在所拥有的,它将无法运作.

$('#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);
    });
Run Code Online (Sandbox Code Playgroud)

Pra*_*Nag 11

$(function(){
   $('#page_background, #header_background').click(function(){

   var id = this.id;
   if(id == 'page_background')
     // page background
   else
     //header 
 });
});
Run Code Online (Sandbox Code Playgroud)

工作小提琴

当你使用这个内部colorpicker onSubmit功能

onSubmit: function(hsb, hex, rgb, el) {
Run Code Online (Sandbox Code Playgroud)

在哪里获得元素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
Run Code Online (Sandbox Code Playgroud)


Jam*_*ice 6

假设您有一个对存储在 中的被点击元素的引用this,您可以简单地使用原生 DOM 属性:

var id = this.id;
Run Code Online (Sandbox Code Playgroud)

如果this是 jQuery 对象,而不是 DOM 节点,则可以使用this.attr("id").

另请注意,这hasClass是一个普通的 jQuery 方法,而不是插件。它是标准 jQuery 库的一部分。