简体   繁体   English

如何使用jQuery更改父元素的背景颜色?

[英]How do I change the background colour of parent element using jQuery?

What I am trying to do is change the background colour of a parent element when a submit button is clicked. 我想做的是单击提交按钮时更改父元素的背景颜色。

So for I have have tried this code: 因此,我已经尝试了以下代码:

            $("input.submit").click(function(){
                var className = $(this).parent().attr("class");
                $(className).animate({backgroundColor: '#FFB95E'}, 1000);
                $(className).animate({borderColor: '#C97200'}, 1000);
            });

But I can never get the class name of the parent element. 但是我永远无法获得父元素的类名。 There are a few submit buttons all with different parent elements, that is why I need to do it this way. 有一些提交按钮都带有不同的父元素,这就是为什么我需要这样做。

Could anyone please help? 谁能帮忙吗?

Many Thanks 非常感谢

Peter 彼得

An example of your markup would help with this problem but you seem to be using the right code to get the parent element. 标记示例可以帮助解决此问题,但是您似乎正在使用正确的代码来获取父元素。

I would suggest you use a debugger like firebug to see what $(this).parent()[0] is or just alert($(this).parent()[0]); 我建议您使用像调试器这样的调试器来查看$(this).parent()[0]是什么,或者只是alert($(this).parent()[0]); if it does not return "object" you know that you don't have a parent element if you do have a parent element use alert($(this).parent()[0].outerHTML); 如果它不返回"object" ,则说明您没有父元素,如果您有父元素,请使用alert($(this).parent()[0].outerHTML); to see how if you have the right element. 看看您是否拥有正确的元素。

Lastly $(className) is redundant and serves no purpose just chain the elemnt commands with the getter like below or use the variable straight it is already a jQuery object. 最后, $(className)是多余的,仅将如下所示的getter链接到elemnt命令是没有用的,或者直接使用已经是jQuery对象的变量。

$(this).parent().animate({backgroundColor: '#FFB95E'}, 1000).animate({borderColor: '#C97200'}, 1000);

Why not simply 为什么不简单

$(this).parent()
       .animate({backgroundColor: '#FFB95E',
                 borderColor: '#C97200'}, 1000);

you don't need to get the class of the parent to set the background color. 您不需要获取父类来设置背景颜色。 however if I'm not mistaken animate on colors does not work by default you'll need some plugin to handle the transitions 但是,如果我没记错的话,在颜色上设置动画在默认情况下不起作用,则需要一些插件来处理过渡

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

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