繁体   English   中英

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

[英]why is this code not targeting the right selector

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

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

我这样称呼它

$('.colorme').click(colorMe);

它改变了这个div的背景

<div class="colorme">Color Me</div>

问题是我想在运行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
});

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

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..
});

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

$(this).colorMe()

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

// css
.red {
    background: red;
}

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

那你就可以做到

$(".a_class").colorMe();
$(".a_class").unColorMe();

您应该使用.addClass()方法。

function colorMe(element){
   element.addClass('my-red-class');
}

$('.colorme').click(function(){      
  colorMe(this);         
});

在你的css文件中你有一个名为'my-red-class'的类(使用更好的名字!)

.my-red-class { background-color: red; }

你也可以轻松删除CSS:

function unColorMe(element){
   element.removeClass('my-red-class');
}
function colorMe(){
    $(this).css('color', 'red');
}

使用call()

$('.colorme').click(function(){
    alert('something happens first, then colorMe is called');
    colorMe.call(this);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM