當頁面加載時,我在 HTML 中有一個輸入,而其他的則是通過 JS 代碼動態創建的。
自動完成功能僅適用于第一個輸入,但不適用于動態創建的輸入。為什么是這樣?
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" autocomplete="off" id="example" name="example[]" placeholder="Example" class="exampleInput" required/></td>
<td><textarea name="ex[]" cols="8" rows="2" placeholder="Example" class="exampleTxtArea" required/></textarea></td>
<td><button type="button" name="addElement" id="addElement" class="btnAddElement"> </button></td>
</tr>
</table>
$(document).ready(function() {
var i = 1;
$('#addElement').click(function() {
i ;
$('#dynamic_field').append('<tr id="row' i '"><td><input type="text"
autocomplete="off" id="example" name="example[]"
placeholder="Example" required/></td>
<td><textarea name="ex[]" cols="8" rows="2"
placeholder="Example"
required/></textarea></td>
<td><button type="button" name="remove" id="' i '"
>-</button></td></tr>');
});
$('#example' i '').autocomplete({
source: 'input_search.php',
});
$(document).on('click', '.btn_removeRow', function() {
var button_id = $(this).attr("id");
$('#row' button_id '').remove();
});
});
uj5u.com熱心網友回復:
主要問題是因為您只autocomplete()在頁面加載時系結。它不會自動將自身應用于您的新內容append()。您需要手動執行此操作。
此外,您還應該進行一些其他更改以提高代碼質量。首先,避免將 HTML 放在 JS 中。您可以使用 atemplate來代替。
此外,切勿將id屬性放在可以動態重復的內容中。這是因為在 DOM 中id 必須是唯一的,重復相同的元素將意味著您的 HTML 無效。
同樣,不要使用id您在運行時創建的增量屬性。它使代碼比它需要的更復雜,并且通常會創建也應該避免的不必要的全域變數。使用公共class屬性按行為對元素進行分組,并在 JS 邏輯中使用 DOM 遍歷來關聯事件處理程式中的元素。
考慮到這些改進,您的代碼將如下所示:
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" autocomplete="off" name="example[]" placeholder="Example" class="exampleInput" required /></td>
<td><textarea name="ex[]" cols="8" rows="2" placeholder="Example" class="exampleTxtArea" required></textarea></td>
<td><button type="button" name="addElement" id="addElement" class="btnAddElement"> </button></td>
</tr>
</table>
<template id="row-template">
<tr>
<td><input type="text" autocomplete="off" id="example" name="example[]" placeholder="Example" class="exampleInput" required /></td>
<td><textarea name="ex[]" cols="8" rows="2" placeholder="Example" class="exampleTxtArea" required></textarea></td>
<td><button type="button" name="remove" class="btn_removeRow">-</button></td>
</tr>
</template>
jQuery($ => {
let rowTemplate = $('#row-template').html();
$('#addElement').on('click', () => {
let $content = $(rowTemplate).appendTo('#dynamic_field');
$content.find('.exampleInput').autocomplete({
source: 'input_search.php'
});
});
$('.exampleInput').autocomplete({
source: 'input_search.php'
});
$(document).on('click', '.btn_removeRow', e => {
$(e.target).closest('tr').remove();
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497875.html
標籤:javascript html jQuery
下一篇:同一個元素中的同一個類
