下面有一个 jQuery,我用它在数据库中添加一些条目。它工作正常。我在同一文件中使用相同的内容来删除一些数据。 remove-from-db 的形式有 id RemoveMe
并将其发布到 $.post("add-to-db.php?id=<?php echo (int)$_GET['id'] ?>"
下面您可以看到表单 ID AddMe
的 add-to-db 脚本。 .
我的问题是是否有办法将这两者合二为一。谢谢。
$(function(){
$("#AddMe").submit(function(e){
e.preventDefault();
$.post("add-to-db.php?id=<?php echo (int)$_GET['id'] ?>", $("#AddMe").serialize(), function (data){
$("#submit").attr('src','http://download.oracle.com/tech/blaf/specs/buttons/actnavbuttons/actnav_disabled_example.gif');
$("#submit").attr('disabled',true);
$("#submit").unbind('click');
$("#message_post").html("Thank you");
setTimeout(function () { $("#message_post").hide(); window.location.href = "product.php?id=<?php echo (int)$_GET['id'] ?>"; }, 2000);
});
});
});
<form id="AddMe">
<input type="image" name="submit" id="submit" src="http://blog.mirthlab.com/wp-content/uploads/2008/04/rollover-up.png">
</form>
<div id="message_post"></div>
<小时/>
$(function(){
$("#RemoveMe").submit(function(e){
e.preventDefault();
$.post("remove-from-db.php?id=<?php echo (int)$_GET['id'] ?>", $("#RemoveMe").serialize(), function (data){
$("#submit").attr('src','http://download.oracle.com/tech/blaf/specs/buttons/actnavbuttons/actnav_disabled_example.gif');
$("#submit").attr('disabled',true);
$("#submit").unbind('click');
$("#message_post").html("Thank you");
setTimeout(function () { $("#message_post").hide(); window.location.href = "product.php?id=<?php echo (int)$_GET['id'] ?>"; }, 2000);
});
});
});
<form id="RemoveMe">
<input type="image" name="submit" id="submit" src="http://blog.mirthlab.com/wp-content/uploads/2008/04/rollover-up.png">
</form>
<div id="message_post"></div>
最佳答案
您可以使用对象文字数组来存储 id 和 url 对
$(function () {
var buttons = [
{ id : '#AddMe', url : 'add-to-db.php' },
{ id : '#RemoveMe', url : 'remove-from-db.php' }
];
$.each(buttons, function(i,v) {
$(v.id).submit(function(e){
e.preventDefault();
$.post(v.url + "?id=<?php echo (int)$_GET['id'] ?>", $(v.id).serialize(), function (data) {
$("#submit")
.attr('src','http://download.oracle.com/tech/blaf/specs/buttons/actnavbuttons/actnav_disabled_example.gif')
.attr('disabled',true)
.unbind('click');
$("#message_post").html("Thank you");
setTimeout(function () {
$("#message_post").hide();
window.location.href = "product.php?id=<?php echo (int)$_GET['id'] ?>";
}, 2000);
});
});
});
});
关于javascript - 如何将两个相同的 jQuery 脚本合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8129808/