[英]jquery : update css on one table column based on attribute of another column
這是我的HTML表格
<!DOCTYPE html>
<html>
<body>
<table>
<thead>
<th>Header1</th>
<th>Header2</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" id=0 /></td>
<td>TEXT1</td>
</tr>
<tr>
<td><input type="checkbox" id=1 checked/></td>
<td>TEXT2</td>
</tr>
</tbody>
</table>
</body>
</html>
我的目標是掃描表中的所有行(在頁面加載后),並通過jquery更新第二列文本的CSS(如鏈接所示)
例如,上表應按上述方式呈現(元素TEXT2被刪除)
我相信我們可以使用jquery的css方法來設置元素的css,如下所示
.css("text-decoration", "line-through")
但是我不知道如何構建一個可以掃描表中所有行並執行css的jquery片段。
在jquery中這真的可能嗎?
任何幫助表示贊賞!
1.初始化腳本
要在頁面加載后運行腳本,請考慮將.on()
方法與load
事件一起使用。
參考: .on()| jQuery API文檔
2.遍歷指定的元素:
要遍歷所需元素,請考慮將.each()
方法與指定的css選擇器td > input
,以直接定位td
元素的嵌套input
元素為目標(從而規避所有嵌套在任何嵌套元素中的input
元素的定位)特定的td
元素,而無需鏈接另一個.find()
方法來指定所需的嵌套元素)。
參考: .each()| jQuery API文檔
3.檢查所需條件:
要驗證所討論的元素是否具有checked
的屬性,請考慮使用條件語句 (如if()
來檢查條件的評估結果是否為true
。
如果是這樣,請在條件語句塊內使用.css()
方法添加所需的內聯樣式 。
參考: .css()| jQuery API文檔
代碼段演示:
$(window).on('load', function(){ $('td > input').each(function(){ if($(this).attr('checked')) { $(this).parent().next().css('text-decoration', 'line-through'); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <th>Header1</th> <th>Header2</th> </thead> <tbody> <tr> <td><input type="checkbox" id="text0" /></td> <td>TEXT1</td> </tr> <tr> <td><input type="checkbox" id="text1" checked/></td> <td>TEXT2</td> </tr> </tbody> </table>
注意:
id="0"
),則id
選擇器無效;值必須以字符串開頭(例如: id="text0"
id="text0"
我在Jquery中做到了:
在已選中復選框的第二列上刪除文本。
但還包括刪除用戶在第二列上的文字的用戶用戶點擊復選框
$(document).ready(function(){ $('input:checkbox').on('change', function () { var inpt = $(this).parent().next('td'); if (this.checked) { $(inpt).css('textDecoration', 'line-through'); } else { $(inpt).css('textDecoration', 'none'); } }); var i= $('input[type=checkbox]:checked').parent().next('td'); if ($('input[type=checkbox]:checked')) { $(i).css('textDecoration', 'line-through'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <table> <thead> <th>Header1</th> <th>Header2</th> </thead> <tbody> <tr> <td><input type="checkbox" id=0 /></td> <td>TEXT1</td> </tr> <tr> <td><input type="checkbox" id=1 checked/></td> <td>TEXT2</td> </tr> </tbody> </table> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.