我有这段JavaScript代码。它似乎在各个方面都起作用,但只有一个。此脚本适用于小型时钟应用程序。在主页上,一些PHP决定是显示"开始"按钮、"停止"按钮还是显示文本区域,以根据数据库中的一些信息记录在记录的时间段内所做的工作。
此JS代码旨在向PHP文件发送AJAX请求,该文件根据当前可见的输入操作数据库。如果PHP脚本没有返回错误,JS应该从DOM中删除当前输入,并将与循环中的下一步相关联的输入添加到DOM中。
我认为这里的问题是,在currentSubmit
的初始元素引用发生变化后,jQuery的.click()
函数没有被触发。
我可能错了,但不管问题是什么,我该如何解决?
if($('input[name="timeclock_input"]').length == 0) {
var currentSubmit = $('input[name="submit_record"]');
} else {
var currentSubmit = $('input[name="timeclock_input"]');
}
var inputValueArray = [
"Start Timeclock",
"Stop Timeclock",
"Add Record"
];
currentSubmit.click(function() {
if (currentSubmit.val() == inputValueArray[0]) {
$.post( "php/record.php", { action: "start" })
.done(function( data ) {
if (data == "success") {
$('input[name="timeclock_input"]').replaceWith('<input type="button" name="timeclock_input" value="Stop Timeclock" />');
currentSubmit = $('input[name="timeclock_input"]');
} else {
alert(data);
}
});
} else if (currentSubmit.val() == inputValueArray[1]) {
$.post( "php/record.php", { action: "stop" })
.done(function( data ) {
if (data == "success") {
$('input[name="timeclock_input"]').replaceWith('<div id="record-container"><textarea name="timeclock_input" placeholder="Description of Work Completed"></textarea><br /><input type="button" name="submit_record" value="Add Record" /></div>');
currentSubmit = $('input[name="submit_record"]');
} else {
alert(data);
}
});
} else if (currentSubmit.val() == inputValueArray[2]) {
$.post( "php/record.php", { action: "record" })
.done(function( data ) {
if (data == "success") {
$('#record-container').replaceWith('<input type="button" name="timeclock_input" value="Stop Timeclock" />');
currentSubmit = $('input[name="timeclock_input"]');
} else {
alert(data);
}
});
}
});
您有三个不同的按钮,可以做三件不同的事情。我会为每个按钮分配一个单独的$.click(function(){...})
。页面加载时,默认(第一个)按钮应可见($.show()
),其他两个按钮应隐藏($.hide()
)。然后在每个if (data == "success"){...}
部分$.hide()
是当前按钮,$.show()
是下一个按钮。
我找到了问题的答案。解决方案是使用这样的事件委派。。。
$('#input-container').on( "click", "input", function() {
Other Code Here...
});