jQuery onclick获取元素ID,使用值作为变量来定位用于更改CSS背景颜色的类 [英] JQuery onclick get element id, use value as variable to target classes for changing css background color
问题描述
我有一个项目列表,每个项目都有一个不同的id
(JS小提琴 https://jsfiddle .net/r45gjykw/2/).用户可以单击列表中的项目,并使用onclick
,JQuery可以获取元素的id
值并将其设置为可变字符串.此字符串值用于更改在class
中带有该值的任何元素的css background-color
:
I have a list of items, each with a distinct id
(JS fiddle https://jsfiddle.net/r45gjykw/2/). The user can click on an item in the list and with onclick
the JQuery gets the id
value of the element and makes it a variable string. This string value is used to change the css background-color
of any element that carries that value in a class
:
因此,单击:
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities" onclick="highlightEntities()">Guilhem Vidal</li>
触发此jQuery操作:
Fires this jQuery action:
function highlightEntities() {
var entclass = $(this).attr('id');
$("."+entclass).css("background-color", "yellow");
}
(例如)应该使用哪个实例:
Which should take any instance of (for example):
<a href="http://somefoosite/Guilhem_Vidal_MSP-AU" class="change_link_colour Guilhem_Vidal_MSP-AU">W<span class="supplied">illelmum</span> Vitalis</a>
...并将背景颜色更改为黄色".
...and change the background colour to "yellow".
如果使用JavaScript更容易做到这一点,我也会接受.
If this is easier done in JavaScript I would accept that too.
在此先感谢您的帮助.
推荐答案
由于使用的是内联绑定,因此应在函数调用中传入this
,以便可以访问单击了哪个元素.但是,我强烈建议您考虑动态绑定.
Since you're using an inline binding, you should pass in the this
on the function call, so you have access to which element was clicked. However, I would highly suggest you look into binding dynamically.
function highlightEntities(element) {
$("."+ element.id).css("backgroundColor", "yellow");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities" onclick="highlightEntities(this)">Guilhem Vidal</li>
</ul>
<a href="http://somefoosite/Guilhem_Vidal_MSP-AU" class="change_link_colour Guilhem_Vidal_MSP-AU">W<span class="supplied">illelmum</span> Vitalis</a>
这篇关于jQuery onclick获取元素ID,使用值作为变量来定位用于更改CSS背景颜色的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!