gpt4 book ai didi

javascript - 动态字符计数

转载 作者:行者123 更新时间:2023-11-28 05:49:11 25 4
gpt4 key购买 nike

我正在使用数据表,将行动态添加到我的表中,我有 3 列,

  1. 索引
  2. 文本
  3. 字符计数

我需要逻辑来实现各自“CharCount”字段中每个“文本”列的字符计数

这是我的代码 -

$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;

$('#addRow').on( 'click', function () {
t.row.add( [
counter,
'<input type="text" id=textBox'+counter+'/>',
'<input type="text" id=counterBox'+counter+' disabled="true"/>'
] ).draw( false );

counter++;
});

// Automatically add a first row of data
$('#addRow').click();
});
<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">

<button id="addRow">Add</button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Index</th>
<th>Text</th>
<th>CharCount</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Index</th>
<th>Text</th>
<th>CharCount</th>
</tr>
</tfoot>
</table>

例如,用户在“文本”列中输入内容,
使用 on keyUp 事件,我需要输入的字符总数
显示在相应的 CharCount 列的文本框中.

最佳答案

您可以使用 jQuery .map()遍历所有领域。

$(document).ready(function(){
var t = $('#example').DataTable();
var counter = 1;
$('#addRow').on( 'click', function () {
t.row.add( [
counter,
'<input type="text" id="textBox'+counter+'" />',
'<input type="text" id="counterBox'+counter+'" readonly />'
] ).draw( false );

counter++;
} );

$(document).on( 'keyup', 'input[id^=textBox]', function () {
$(this).parents('tr').find('input[id^=counterBox]').val($(this).val().length);
} );

// Automatically add a first row of data
$('#addRow').click();
});
<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<button id="addRow">Add</button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Index</th>
<th>Text</th>
<th>CharsLeft</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Index</th>
<th>Text</th>
<th>CharsLeft</th>
</tr>
</tfoot>
</table>

关于javascript - 动态字符计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38229156/

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