event.preventDefault prevents ajax call
我一直在尝试让Ajax调用在onclick事件触发的函数内部工作。使用event.preventdefault时,不会重新加载页面,但Ajax调用不起作用,不会向数据库中添加任何数据。当我注释掉这一行时,页面会重新加载,但其他一切都可以工作。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function clickFunction(elem) { var var1 = elem.id; var var2 = var1.split("_"); // elem.preventDefault(); if (var2[0] =="Add") { if (var2[1] =="Calls") { console.log("Calls"); console.log(var1); event.preventDefault(); var data = $(this).serialize(); $.post('progressSheetDynamic', data).done(function (response){ $(".1").html(parseInt($('.1').html(), 10)+1); Calls.update(50); }); } } } | 
HTML代码
| 1 2 3 4 5 | <form action="{{ route("progressSheetDynamic") }}" method="post" id= {{ $addID }}> <input name="increment" value="increment" type="hidden"> </input> <input type="hidden" name="id" value= {{$activities}} > <button type="submit" class="styleHover styleButton" onclick="clickFunction(this)" id= {{ 'Add_'.$newText }}> + </button> </form> | 
我已经检查了日志,函数将进入if语句。我还尝试在按钮单击事件上使用preventdefault,方法是执行elem.preventdefault();但这不起作用。也不使用return false。
问题似乎与这一行有关:
| 1 | var data = $(this).serialize(); | 
应该是这样的:
| 1 | var data = $(elem.form).serialize(); | 
函数中的
如注释所述,
属性:
| 1 | onclick="clickFunction(this, event)" | 
功能:
| 1 2 3 | function clickFunction(elem, event) { // ... } | 
注意,ie8和更低版本没有
当您将
但是button没有
其次,$(this)是引用窗口,它应该是$(elem.form)。
下面是我如何在不改变你的结构的情况下解决你最初的问题。
html:(在
| 1 | <button type="submit" class="styleHover styleButton" onclick="clickFunction()" id= {{ 'Add_'.$newText }}> + </button> | 
javascript:(对elem使用event.target,对$(this)使用$(elem.form)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function clickFunction(event) { var elem = event.target; // event.target will be equivalent to your elem var var1 = elem.id; var var2 = var1.split("_"); event.preventDefault(); if (var2[0] =="Add") { if (var2[1] =="Calls") { console.log("Calls"); console.log(var1); event.preventDefault(); var data = $(elem.form).serialize(); // should be elem.form here to get correct data $.post('progressSheetDynamic', data).done(function (response){ $(".1").html(parseInt($('.1').html(), 10)+1); Calls.update(50); }); } } } | 
不会定义
改为
然后更改函数声明:
| 1 2 3 4 | function clickFunction(event) { console.log(event) ... } | 
如果你想要按钮和事件,看看我有什么:
| 1 2 3 4 5 6 7 8 9 | <button type="submit" class="styleHover styleButton" onclick="clickFunction(event, this);" /> function clickFunction(event, elem) { console.log(event); console.log(elem); event.preventDefault(); } |