2010-11-12 53 views
1

我有一大堆的領域,其中一些具有像使用jQuery .attr設置一個變量,然後改變它

<input id="1" /><label for="1" /> 
<input id="2" /> 
<input id="3" /><label for="3" /> 

標籤對於每一個標籤,我想這樣做

var for_label = $(label).attr("for"); 

然後使用該變量將樣式應用於相應的輸入字段。我應該怎麼做?我非常感謝一個例子,我很新的Javascript ...

+2

ID不應以數字開頭。 – 2010-11-12 18:00:42

+0

感謝一堆,它只是一個例子thoght,實際的html更復雜! – Himmators 2010-11-12 18:02:13

+0

@felix,我知道這不是一個好習慣,但爲什麼我們不應該有數字作爲ID ..,這是不允許的或它只是一個說服。 – kobe 2010-11-12 18:02:21

回答

4
$('label').each(function() { 
    // Get corresponding input element: 
    var input = $('#' + $(this).attr('for')); 
    // apply some CSS class 
    input.css('someStyle'); 
}); 

作爲一個方面說明ids不能以數字開頭。

+0

達林 - 我認爲'

+0

你可以做'this.for'嗎?我想你必須寫'this [0] .for' – hunter 2010-11-12 18:10:30

+0

因爲'$()'函數返回一個jquery對象。使用'this.for'來獲得id。 – 2010-11-12 18:11:03

1

$(label).attr("for")將返回標籤的編號,using the attr method。然後你想要select the element with that id所以:$("#" + $(label).attr("for"))現在你已經選擇了輸入元素。你可以用.css()改變它的風格。例如:$("#" + $(label).attr("for")).css("color", "blue")To loop through all the labels you can d o:

$("label").each(function(){ 
    $("#" + $(this).attr("for")).css("color", "blue");//note that this refers to the label in this context 
}); 
相關問題