2010-08-03 65 views
1

我想爲行添加Title屬性,並且從行的隱藏的兄弟中檢索值,除非單擊。我想使它足夠通用,以便在某些屏幕沒有隱藏文本的行時進行處理。想要簡化添加基於兄弟文本的屬性

這裏是工作的第一關:

$(function() { 
    $("td.commandText pre").each(function(index) { 
    $(this).parent().parent().prev().attr('Title', $(this).text()); 
    }); 
}); 

任何想法,以使更多的優雅?

這裏是我一起工作的HTML表的例子:

<table class="maingrid"> 
    <thead> 
    <tr> 
     <th>Session ID</th> 
     <th>User Name</th> 
     <th>Start Time</th> 
     <th>End Time</th> 
    </tr> 
    </thead><tbody> 
    <tr class="record"> 
     <td id="174">174</td> 
     <td>user1</td> 
     <td>8/2/2010 4:00:09 PM</td> 
     <td></td> 
    </tr> 
    <tr> 
    <td class="details hide commandText" colspan="4"> 
     <pre>Sample Text to show as a tooltip</pre></td> 
    </tr> 
    <tr> 
    <td class="details hide" colspan="4" style="color:red"><pre>no errors</pre></td> 
    </tr> 
    <tr class="record"> 
     <td id="175">175</a></td> 
     <td>user1</td> 
     <td>8/2/2010 4:00:09 PM</td> 
     <td></td> 
    </tr> 
    <tr> 
    <td class="details hide commandText" colspan="4"> 
     <pre>Sample Text to show as a tooltip</pre></td> 
    </tr> 
    <tr> 
    <td class="details hide" colspan="4" style="color:red"><pre>no errors</pre></td> 
    </tr> 
</tbody> 
</table> 
+0

@Felix - 我覺得他只是在解釋它的推理方式,並不是說這是當前代碼的問題:) – 2010-08-03 18:46:52

+0

@Nick:好的... – 2010-08-03 18:48:21

回答

1

您可以使用.closest()使它有點短,像這樣:

$(function() { 
    $("td.commandText pre").each(function(index) { 
    $(this).closest('tr').prev().attr('Title', $(this).text()); 
    }); 
}); 

其他,有沒有更多的優雅在這裏獲得。