![](/img/trans.png)
[英]How to apply a CSS property to an element using it's CSS path in Javascript?
[英]How to get the id of an element and apply it as a CSS property?
<ul> <li> <span class="circle" id="beige"></span> <span>Beige</span> </li> <li> <span class="circle" id="black"></span> <span>Black</span> </li> <li> <span class="circle" id="blue"></span> <span>Blue</span> </li> </ul>
我想從圓形類中選擇ID,並將該ID作為背景色應用於同一類。
我的jQuery是:
$('span.circle').each(function (index, element) {
$(element).css({
'background-color': $('.circle').attr('id')
});
});
但是,當我這樣做時,它僅選擇第一個span元素的id並將該id顏色應用於同一類的所有其他span。 知道如何選擇不同的ID,以便在不同跨度上具有不同的背景顏色嗎?
提前致謝
使用css()
方法的匿名函數:
$('.circle').css('background-color', function () {
return this.id;
});
該方法本身(與大多數jQuery方法一樣)在調用它的集合上進行迭代,在匿名函數中, this
指向迭代在其上移動的特定元素。
順便說一句,原因是:
$('.circle').attr('id');
不能正常工作是因為每次您重新選擇整個集合,然后調用attr()
方法的getter版本時,該方法在集合上調用時僅返回該集合的第一個元素的結果。
而且,順便說一句,當您有權訪問DOM節點時,請勿使用jQuery檢索id
:
$(DOMElementReference).attr('id');
和:
$(DOMElementReference).prop('id');
只是以下產品的昂貴版本:
DOMElementReference.id;
參考文獻:
css()
。 嘗試在each
的上下文中引用元素:
$('span.circle').each(function(index, element) {
$(element).css({
'background-color': $(element).attr('id');
});
});
我正在使用vars使其更易於理解。 $(this)將在每次迭代中引用當前元素。 我將其分配給'$ this'變量,因此我們不會多次運行選擇器。
$('span.circle').each(function() {
var $this = $(this),
elementId = $this.attr('id');
$this.css({'background-color': elementId});
});
這是有效的代碼 HTML中也存在錯誤,跨度未正確放置
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Drag Me</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li> <span class="circle" id="beige">
<span>Beige</span>
</span>
</li>
<li> <span class="circle" id="black">
<span>Black</span>
</span>
</li>
<li> <span class="circle" id="blue">
<span>Blue</span>
</span>
</li>
</ul>
<script>
$(document).ready(function() {
$('span.circle').each(function(index, element) {
console.log($(element).attr('id'));
$(element).css(
'color', $(element).attr('id'));
});
});
</script>
</body>
</html>
代替:
$('.circle').attr('id')
是:
element.id
像這樣的東西:
$('span.circle').each(function(index, element) {
$(element.id).css('background-color', element.id);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.