gpt4 book ai didi

javascript - 如何从 select2 关闭按钮获取最接近的 id?

转载 作者:行者123 更新时间:2023-12-02 19:02:27 25 4
gpt4 key购买 nike

我正在使用Select2 Multiple Selection

点击x我想要表格行的ID

enter image description here

这是一个可以看到真正问题的代码片段。 https://jsfiddle.net/ja1omn9x/

我正在使用此代码:

但它给了我未定义应该怎样做?

$(document).on('click', '.select2-selection__choice__remove', function(e) {
console.log("YES: ", $(this).closest('tr').attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr id="row1">
<td data-select2-id="4">
<select name="product_id[]" class="invoiceProducts">
<option value="12" data-select2-id="19">Orange</option>
<option value="14" data-select2-id="20">Apple</option>
</select>
<span class="select2>
<span class=" selection ">
<span class="select2-selection select2-selection--multiple ">
<ul class="select2-selection__rendered ">
<li class="select2-selection__choice " title="Apple " data-select2-id="23 ">
<span class="select2-selection__choice__remove " role="presentation ">×</span>Apple</li>
</ul>
</span>
</span>
<span class="dropdown-wrapper " aria-hidden="true ">
</span>
</span>
</td>
</tr>

最佳答案

您可以使用 select2:unselecting 每当您单击 x 按钮时都会调用它,然后您可以使用 .closest("tr").prop( "id") 获取行的 id。

演示代码:

$(".js-example-basic-multiple-limit").select2({
maximumSelectionLength: 2
});

$('.js-example-basic-multiple-limit').on('select2:unselecting', function(e) {
console.log('I am in :)');
console.log("YES: ", $(this).closest('tr').prop('id'));
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a091f161f190e483a4e544b544a57181f0e1b544b" rel="noreferrer noopener nofollow">[email protected]</a>/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6310060f0600175123574d524d534e010617024d52" rel="noreferrer noopener nofollow">[email protected]</a>/dist/js/select2.min.js"></script>

<table>
<tr id="row1">
<td>
<select class="form-control js-example-basic-multiple-limit" multiple="multiple">
<option selected="selected">orange</option>
<option>white</option>
<option selected="selected">purple</option>
</select>
</td>
</tr>
<tr id="row2">
<td>
<select class="form-control js-example-basic-multiple-limit" multiple="multiple">
<option selected="selected">orange</option>
<option>white</option>
<option selected="selected">purple</option>
</select>
</td>
</tr>
</table>

关于javascript - 如何从 select2 关闭按钮获取最接近的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65389825/

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