简体   繁体   English

jQuery阻止输入默认操作

[英]jQuery prevent input default action

I have an ajax form I would like to prevent from preforming an action when submitted and have tried numerous methods and nothing works. 我有一个ajax表单,我想阻止在提交时执行一个动作,并尝试了很多方法,没有任何作用。 My first method was: 我的第一种方法是:

 return false;

and then I tried 然后我尝试

event.preventDefault();

event being the callback name or whatever you call it. event是回调名称或任何你称之为的回调名称。

function(event) {
    event.preventDefault();
};

Heres the HTML I am using right now: 下面是我正在使用的HTML:

<form class="main_search" method="POST" action="ajaxsearch.php">
    <input type="text" class="editable" placeholder="Search">
</form>

Heres the test javascript I set up: 继承人我设置的测试javascript:

$('.main_search').submit(function(event) {
    event.preventDefault(console.log(event)); //Log the event if captured
});

Neither method works but the weird part is that they work on different things like buttons but they don't work on this one form. 这两种方法都不起作用,但奇怪的是它们可以处理不同的东西,比如按钮,但它们不适用于这种形式。 Am I missing something here? 我在这里错过了什么吗? Thanks! 谢谢!

To deal with your specific problem (ie, inserting dynamically generated form ), use $.on() . 要处理您的特定问题(即插入动态生成的表单 ),请使用$.on() You're better off not using document.body as the parent observer (as $.live() essentially does) with $.on() , so the following would be appropriate (considering your actual markup): 您最好不要将$.on()document.body用作父观察器(基本上像$.live()一样$.on() ,因此以下内容将是适当的(考虑您的实际标记):

<div id="searches">
    <form class="main_search" method="POST" action="ajaxsearch.php">
        <input type="text" class="editable" placeholder="Search">
    </form>
</div>

var $main_search = $('.main_search'),
    $searches = $('#searches');

$searches.on('submit', '.main_search', function(event) {
    event.preventDefault();
    console.log(event); //Log the event if captured
});

setInterval(function(){
    $searches.append($main_search.clone());
}, 5000);

http://jsfiddle.net/5TVGn/2/ http://jsfiddle.net/5TVGn/2/

I set up a JSfiddle: 我设置了一个JSfiddle:

http://jsfiddle.net/XM679/ http://jsfiddle.net/XM679/

Could it be you forgot to wrap it into $(document).ready(function() {} ? If this didn't solve the problem: Since the fiddle is working - we would need your context to help more. 如果您忘了将其包装到$(document).ready(function() {}吗?如果这不能解决问题:由于小提琴正在工作-我们需要您的上下文来提供更多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM