简体   繁体   English

CSS仅将class或CSS赋予选定的元素

[英]CSS give class or css to only selected element

I have group of unordered list. 我有一组无序列表。 I have create some function that make every list is clicked, it will run a JS Function. 我创建了一些使每个列表都被单击的函数,它将运行一个JS函数。 Now I want to add some css, if the list is clicked, its bg color will changed. 现在,我想添加一些CSS,如果单击列表,其bg颜色将更改。 My code so far: 到目前为止,我的代码:

 function getDealsTable(obj) { var tenor = obj.innerHTML; $(this).closest('li').css('background-color: rgba(86, 142, 175, 1) !important'); $(this).closest('li').siblings('li').css('background-color: rgba(15, 86, 132, 1) !important'); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class='tenors'> <li onclick='getDealsTable(this);'>12x</li> <li onclick='getDealsTable(this);'>24x</li> <li onclick='getDealsTable(this);'>36x</li> <li onclick='getDealsTable(this);'>48x</li> </ul> 

Unfortunately it doesn't works. 不幸的是,它不起作用。 I have tried to change it to a class, but still not working. 我试图将其更改为一类,但仍无法正常工作。 Anyone can help me? 有人可以帮助我吗? Thanks 谢谢

In order to use !important with jQuery, you need to have 2 parameters. 为了在jQuery中使用!important ,您需要有2个参数。 The first parameter is cssText , the second is the text you want to set as explained here 第一个参数是cssText ,第二个参数是您要设置的文本,如此处所述

Example: 例:

$('.selector').css('cssText', 'color: red !important;')

You can also create the click event using on directly in the javascript, no need to place it on the html element. 您也可以直接在javascript中使用on创建click事件,而无需将其放置在html元素上。

 $('ul.tenors > li').on('click', function() { // Reset all the li colors (must come first) $('ul.tenors > li').css('cssText','background-color: rgba(86, 142, 175, 1) !important;'); // Set the color of the clicked li item (must come second) $(this).css('cssText', 'background-color: rgba(15, 86, 132, 1) !important;'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class='tenors'> <li>12x</li> <li>24x</li> <li>36x</li> <li>48x</li> </ul> 

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

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