gpt4 book ai didi

javascript - Jquery - 限制元素的插入

转载 作者:行者123 更新时间:2023-11-30 20:35:12 30 4
gpt4 key购买 nike

我正在尝试在我的表中创建一个转发器字段。

基本上我想要以下行为:

  1. 如果没有“Test Product2”被添加到表中,用户不能在下面添加其他字段。
  2. 如果“测试产品 2”已添加到表中,则允许用户在下方添加一个字段,并可以在新的蓝色按钮旁边添加另一个“测试产品 2”。

下面是行为的第二种情况的示例。

enter image description here

$(".btn.btn-dark.btn-sm.product2").on("click", this.clickDispatcherTable.bind(this))
//$(".btn.btn-primary.btn-sm").on("click", this.ourClickDispatcher.bind(this));
$("#miningTable").on("click", ".btn.btn-primary.btn-sm.product2", this.ourClickDispatcher.bind(this));

function clickDispatcherTable(e) {
let plusButton = $(e.target).closest(".btn.btn-dark.btn-sm")

if (plusButton.hasClass("product2")) {
let plusButtonParent = plusButton[0].parentElement.parentElement;
plusButtonParent.insertAdjacentHTML('afterend', `
<tr>
<td></td>
<td>
<button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
Add Product2
</button>
</td>
</tr>
`)
}
}

function ourClickDispatcher(e) {

let targetButton = $(".btn.btn-primary.btn-sm.product2")

let targetButtonParent = targetButton[0].parentElement

targetButtonParent.insertAdjacentHTML('beforebegin', `
<td>
<img src="" alt="" height="42" width="42">
<a href="">
Test Product2
</a>
</td>
`)

targetButton.attr('class', 'btn btn-danger btn-sm product2'); // change button class to red

targetButton.text(function() {
return $(this).text().replace("Add", "Edit");
});
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="miningTable" style="float: left;" class="table table-bordered">
<tbody>
<tr>
<td>Product 2</td>
<td>
<button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
Add Product2
</button>
<button type="button" class="btn btn-dark btn-sm product2">+</button>
</td>
</tr>
<tr>
<td>Product 3</td>
<td>
<button type="button" data-exists="product3" class="btn btn-primary btn-sm product3">
Add Product3
</button>
</td>
</tr>
<tr>
<td>Product 4</td>
<td>
<button type="button" data-exists="product4" class="btn btn-primary btn-sm product4">
Add Product4

</td>
</tr>
</tbody>
</table>

正如您在上面的示例中看到的,用户可以根据需要添加多个字段。目前没有限制。

如果不满足条件,如何限制用户添加字段有什么建议吗?

感谢您的回复!

最佳答案

如果我正确理解你的问题,认为这就是你的答案

function clickDispatcherTable(e) {
let plusButton = $(e.target).closest(".btn.btn-dark.btn-sm")
let sw = true;
$( "tbody tr" ).each(function(index, row) {
if(row.children.length != 3) {
sw = false;
}
});

if (sw) {
$('tbody tr:last').after(`
<tr>
<td></td>
<td>
<button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
Add Product2
</button>
</td>
</tr>`)
}
}

关于javascript - Jquery - 限制元素的插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915352/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com