为什么此代码不针对正确的选择器

zmo*_*mol 6 javascript jquery

此函数应该更改被单击对象的背景颜色

function colorMe(){
   $(this).css('background-color', 'red');
}
Run Code Online (Sandbox Code Playgroud)

我这样称呼它

$('.colorme').click(colorMe);
Run Code Online (Sandbox Code Playgroud)

它改变了这个div的背景

<div class="colorme">Color Me</div>
Run Code Online (Sandbox Code Playgroud)

问题是我想在运行colorMe之前做一些其他事情.所以我不能只使用$('.colorme').click(colorMe);.我想要做的就是这样

$('.colorme').click(function(){
  alert('something happens first, then colorMe is called');
  colorMe();         //I call colorMe here..
  $(this).colorMe(); //I also tried this, but it's not working
});
Run Code Online (Sandbox Code Playgroud)

但它并没有影响div.我认为它失去了影响div的轨道.我需要传递它吗?

Rob*_*bin 5

function colorMe(elt){
   $(elt).css('background-color', 'red');
}

$('.colorme').click(function(){
  alert('something happens first, then colorMe is called');
  colorMe(this);         //I call colorMe here..
});
Run Code Online (Sandbox Code Playgroud)

像在这里一样调用jQuery对象上的函数

$(this).colorMe()
Run Code Online (Sandbox Code Playgroud)

你必须建立一个插件(我编辑它来添加一个类)

// css
.red {
    background: red;
}

// js
(function($) {
    $.fn.extend({
        colorMe: function() {
            this.addClass("red");
        },
        unColorMe: function() {
            this.removeClass("red");
        }
    });
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

那你就可以做到

$(".a_class").colorMe();
$(".a_class").unColorMe();
Run Code Online (Sandbox Code Playgroud)