8

我知道有一个名为 .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);
    });
4

2 回答 2

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

   var id = this.id;
   if(id == 'page_background')
     // page background
   else
     //header 
 });
});

工作小提琴

当您在颜色选择器onSubmit功能中使用它时

onSubmit: function(hsb, hex, rgb, el) {

你在哪里得到元素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
于 2012-06-04T17:31:36.303 回答
6

假设您有一个对存储在 中的 clicked 元素的引用this,您可以简单地使用本机 DOM 属性:

var id = this.id;

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

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

于 2012-06-04T17:30:27.887 回答