所以我有这个javascript函数
function validation(step){
var lines = [];
$.each($('#part1row').find('.countall').html().split(/<br\s*\/?>/), function(i, line){
var lineremnbsp = line.replace(/ /gi,'');
var lineremspace = lineremnbsp.replace(/ /gi,'');
if(lineremspace != ''){
lines.push(parseInt(lineremspace));
}
});
var sum = lines.reduce(getSum, 0);
console.log(sum);
if (sum !== 100){
var countall = false;
}
if (countall == false){
$.toast({
heading: 'Alert',
text: 'Jumlah Field Weight harus 100%',
position: 'top-right',
loaderBg: '#FFC107',
icon: 'warning',
hideAfter: 3500
});
return false;
}
if (countall == true){
return true;
}
}
}
验证函数是针对这个特定的 td,它是 .countall
class 的 td,
this is the table , the red box is the td with countall class
问题是,如图所示,我有一个“添加更多”按钮,当我添加新行时,验证函数会忽略新行中的 countall 类,任何人都知道如何解决这个问题 ? , 谢谢你的帮助
编辑 2 --------------------------
这是添加更多功能
function addMore(){
var step = '<?=$pmpdocument->completion?>';
if (step == 'step1') {
var content = '<tr>'+
'<td class="editable" data-step="step1">Double Click to Edit...</td>'+
'<td class="editable advance" data-step="step1">Double Click to Edit...</td>'+
'<td class="editable numberonly countall" data-step="step1">Double Click to Edit...</td>'+
'<td class="marked numberonly" data-step="step3"> </td>'+
'<td class="marked numberonly" data-step="step4"> </td>'+
'<td class="marked" data-step="step4"> </td>'+
'<td data-step="step5" class="numberonly"> </td>'+
'<td data-step="step5" class="numberonly"> </td>'+
'<td data-step="step5"> </td>'+
'<td data-step="step5"> </td>'+
'</tr>';
$("#part1row").append(content);
var newnumber = parseInt($("#part1row").attr('data-row')) + 1;
$("#part1row").attr('data-row', newnumber);
var datarow = parseInt($("#part1row").attr('data-row'));
if (datarow > 1) {
$("#removerow").show();
} else {
$("#removerow").hide();
}
}
}
我一直在谷歌上找它,很多人只谈论动态元素的点击功能,比如你应该使用的动态元素
$(document).on('click', '#idname', function(){});
代替
$(#idname).on('click', function(){});
它适用于动态元素,我也将它用于项目,但我仍然不知道如何重新调用验证函数来重新检测新的 DOM 元素,如果有人知道如何这样做,这将非常有帮助,再次感谢您的帮助
最佳答案
我尝试更改代码
$.each($('.countall[data-step="1"]').html().split(/<br\s*\/?>/), function(i, line){
var lineremnbsp = line.replace(/ /gi,'');
var lineremspace = lineremnbsp.replace(/ /gi,'');
if(lineremspace != ''){
lines.push(parseInt(lineremspace));
}
});
到
$('.countall[data-step="step1"]').each(function(key, val){
var liness = $(this).html().split(/<br\s*\/?>/);
$.each(liness, function(i, line){
var lineremnbsp = line.replace(/ /gi,'');
var lineremspace = lineremnbsp.replace(/ /gi,'');
if(lineremspace != ''){
lines.push(parseInt(lineremspace));
}
})
});
最终成功了
关于动态元素的 foreach 类上的 Javascript 函数脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45615425/