向子元素和父元素添加和删除类



当我点击"客户行"时,它应该在"运营商层"中添加类"开放运营商层(open carrier tiers("。这是有效的。但当我点击"carrier-tiers close-btn"时,它应该从其父元素中删除之前添加的相同类。这不起作用。我使用$(this(是因为整个代码在页面上重复多次。

<tr class="customer-row">
<td class="carrier-tiers">
<div class="content-box">
<li class="carrier-tiers-close-btn">close</li>
<form action="" method="POST">
<input type="text" name="Customer Name">
<button type="submit">Submit</button>
</form>
</div>
</td>
</tr>

Jquery

$(".customer-row").click(function () {
$(this).find("td.carrier-tiers").addClass('open-carrier-tiers');
});
$(".carrier-tiers-close-btn").click(function () {
$(this).parent().parent().removeClass('open-carrier-tiers');
});

我认为这是因为每当单击行时都会触发关闭事件,因为该事件会冒泡。若要解决此问题,请向事件处理程序中添加一个event.stopPropion((。这将防止行单击也触发关闭。请尝试下面的代码片段,看看它是否适合您。

$(".customer-row").click(function(e) {
$(this).find("td.carrier-tiers").addClass('open-carrier-tiers')
e.stopPropagation();
console.log(document.querySelector("td.carrier-tiers").className);
});
$(".carrier-tiers-close-btn").click(function(e) {
$(this).parent().parent().removeClass('open-carrier-tiers');
e.stopPropagation();
console.log(document.querySelector(".carrier-tiers-close-btn").className);
});
td {
padding: 0.5em;
border: 1px solid lightgray;
}
<table>
<tbody>
<tr class="customer-row">
<td>customer-row</td>
<td class="carrier-tiers">
<div class="content-box">
<li class="carrier-tiers-close-btn">close</li>
<form action="" method="POST">
<input type="text" name="Customer Name">
<button type="submit">Submit</button>
</form>
</div>
</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

考虑使用更精确的选择器。

$(function() {
$(".customer-row td:eq(0)").click(function() {
$(this).next("td.carrier-tiers").addClass('open-carrier-tiers');
});
$(".carrier-tiers-close-btn").click(function() {
$(this).closest('.open-carrier-tiers').removeClass('open-carrier-tiers');
});
});
.open-carrier-tiers {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="customer-row">
<td>customer-row</td>
<td class="carrier-tiers">
<div class="content-box">
<ul>
<li class="carrier-tiers-close-btn">close</li>
</ul>
<form action="" method="POST">
<input type="text" name="Customer Name">
<button type="submit">Submit</button>
</form>
</div>
</td>
</tr>
</tbody>
</table>

当您瞄准Row时,子项上的单击事件不会弹出。

最新更新