2012-10-17 128 views
0

我對jQuery非常陌生,我想根據頁面加載時的值設置元素的背景顏色。jQuery:爲元素分配背景顏色

每個元素都有id"*_hex"這就是爲什麼我使用選擇$("[id$=_hex]")結束,並且均具有value這是一個十六進制顏色。

這裏是個例元素:

<input id="product_colors_attributes_382873_hex" type="text" value="#c22424"> 

而這裏的代碼,我來了這麼遠:

$(document).ready(function(){ 
$("[id$=_hex]").each(function(){ 
     $(this).css('backgroundColor', $(this).value); 
    }); 
}); 

它的工作原理,如果我硬編碼的顏色,但顯然$(this).value沒有按」工作。 任何線索? 在此先感謝。

回答

3

您應該可以使用this.value,不需要jQuery來獲取輸入的值。的$(this).value

$(this).val() 
2
$(this).css('backgroundColor', $(this).val()); 
3

使用val(),而不是要與jQuery訪問值字段,你應該使用功能VAL()

$(document).ready(function(){ 
$("[id$=_hex]").each(function(){ 
     $(this).css('backgroundColor', $(this).val()); 
    }); 
}); 
1