我有一个关于如何使用 css 类选择器更新同一行中的列的问题。以下是示例场景。
项目 | 价格 | 折扣 |
最终价格 |
---|---|---|---|
手机 | 500 | 10 | 450 |
笔记本电脑 | 1000 | 20 | 800 |
从上表中,折扣列每行都有文本字段。当用户输入折扣百分比时,该行的最终价格会相应更新。
假设“最终价格”列具有类属性(.final-price)。
请让我知道此场景的 css 选择器,以便我可以在 JavaScript 中使用它?
提前致谢。
斯里
我已经尝试过:
我尝试使用CSS中的siblings()函数,但最终使用了number,siblings()[3]。不知何故,我需要动态地进行此操作(而不是编号)。
你有这样的结构:
<tr>
<td>Mobile</td>
<td>500</td>
<td>
<input type="text" />
</td>
<td class="final-price">450</td>
</tr>
没有选择器可以在 CSS 中向上选择另一个父元素中的元素。所以你需要分两步完成:
const $table = $("table")
$table.on("input", event => {
const $input = $(event.target),
$tdFinalPrice = $input.closest("tr").find(".final-price")
$tdFinalPrice.css("background-color", "red")
})
* {
box-sizing: border-box;
}
body {
margin: 0;
}
table {
width: 100%;
max-width: 1000px;
border-color: #ddd;
border-collapse: collapse;
}
table, input {
padding: 10px;
/* font */
color: #000;
font-family: "Segoe UI";
font-size: 19px;
}
tr {
border-width: 1px 0;
border-color: inherit;
border-style: solid;
}
th {
background-color: #eee;
}
th,
td {
position: relative;
width: calc(100% / 4);
padding: 10px;
border-width: 0 1px;
border-color: inherit;
border-style: solid;
}
input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Item</th>
<th>Price</th>
<th>Discount</th>
<th>Final Price</th>
</tr>
<tr>
<td>Mobile</td>
<td>500</td>
<td>
<input type="text" />
</td>
<td class="final-price">450</td>
</tr>
<tr>
<td>Laptop</td>
<td>1000</td>
<td>
<input type="text" />
</td>
<td class="final-price">800</td>
</tr>
</table>