簡體   English   中英

jQuery:根據另一列的屬性更新一個表列上的CSS

[英]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> 

注意:

  1. 如果值以整數(數字/單位值)開頭(例如: id="0" ),則id選擇器無效;值必須以字符串開頭(例如: id="text0"
  2. 將屬性值包裝在撇號中,例如: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM