2014-01-30 44 views
0

我對jQuery來說很新,所以對我來說很簡單。爲相對元素設置CSS

使用下面的HTML:

<table border="1"> 
<tr> 
    <td headers="QTY"> 
    <input type="hidden" name="f50" value="1"> 
    </td> 
    <td headers="COLOR"> 
    <input type="text" name="f01"> 
    </td> 
</tr> 
<tr> 
    <td headers="QTY"> 
    <input type="hidden" name="f50" value="0"> 
    </td> 
    <td headers="COLOR"> 
    <input type="text" name="f01"> 
    </td> 
</tr> 
</table> 

我努力做到以下幾點:

  1. 對於每一行
  2. 看看隱藏的項目 「F50」
  3. 的價值如果值= 1,則將同一行的f01的背景顏色設置爲綠色
  4. 如果值!= 1,則將th F01電子背景色爲黃色同一行

到目前爲止,我有這樣的:

$('input[name="f50"]').each 
(
function(index) 
{ 
    var theItem = this; 

    if (parseInt(theItem.value) == 1) 
    { 
    alert ('Make Green'); 
    } 
    else 
    { 
    alert ('Make Yellow'); 
    } 
} 
); 

我不知道我如何引用從我所在的地方相對F01元素。

任何幫助,非常感謝。

乾杯

Duncs

+0

它是一個擁有許多值的數組。 ID應該是唯一的,名稱可以用於表格形式的多個項目。 – dunkyduncs

+0

也更好地使用class =「f50」,並讓jQuery在類上工作。 – Lexib0y

+0

好,但我原來的問題仍然存在:) – dunkyduncs

回答

3

,如果他們在同一個TR,您可以用closest('tr')尋父TR,以及find這個TR得到需要的元素。

var closestf01 = $(this).closest('tr').find('input[name="f01"]'); 

然後

closestf01.css('background-color', 'yellow'); // or green 

所以

$('input[name="f50"]').each(function(index) { 
    var f01 = $(this).closest('tr').find('input[name="f01"]'); 
    if ($(this).val() == 1)//or this.value == 1 
     f01.css('background-color', 'yellow'); 

    else 
     f01.css('background-color', 'green'); 
}); 

或 「短」

$('input[name="f50"]').each(function(index) { 
     $(this) 
      .closest('tr') 
      .find('input[name="f01"]') 
      .css('background-color', (this.value == 1 ? 'yellow' : 'green')); 
}); 

看到jsfiddle

+0

太棒了。爲此歡呼。看起來很簡單,一旦你有一個工作的例子。非常感謝。 Duncs – dunkyduncs

0

試試這個:

$('input[name="f50"]').each(function() { 
    var this_val = $(this).val(); 

    if (this_val == 1) { 
     alert("Make Green"); 
     $(this).addClass('green'); 
    } else { 
     alert('Make Yellow'); 
     $(this).addClass('yellow'); 
    } 
}); 

FIDDLEhttp://jsfiddle.net/txw66/2/

+0

另外,您應該使用關鍵字'var'來聲明變量:'var this_name = ...' – RononDex

+0

'this_name'似乎沒有被使用。最好在你的答案中解釋代碼,以便OP可以學習。 – ajp15243

+0

我會給這個去看看它是否工作。感謝您花時間回覆。正如我上面所說。看到一個可行的例子真的很有幫助。乾杯,Duncs – dunkyduncs

0

試試這個

$('input[name="f50"]').each 
(
function(index) 
{ 
    var theItem = this; 

    if (parseInt(theItem.value) == 1) 
    { 
    $(theItem).parent().next().find('input[name="f01"]').css('background-color','green'); 
    } 
    else 
    { 
    $(theItem).parent().next().find('input[name="f01"]').css('background-color','yellow'); 
    } 
} 
); 

http://jsfiddle.net/HFV9N/

0

我會嘗試:

$('[name="f50"][value="1"]').closest('tr').find('[name="f01"]').css('background-color','green'); 
$('[name="f50"]:not([value="1"])').closest('tr').find('[name="f01"]').css('background-color','yellow'); 

如@RononDex所述,名稱屬性應該是唯一的 - 使用此屬性的全局選擇器不保證可在所有瀏覽器中使用。您應該考慮使用data-blahblah屬性,而不是像<input type="hidden" data-which="f50" value="1" />

相關問題