1

有一个注册表,我检查用户名是否可用。如果可用,则在用户名字段旁边显示一个文本进入段落(“可用!”),如果不可用(“不可用!”)。如果用户名不可用,我不想提交。

<script type ="text/javascript">

$(function(){
    $('#usernameFeedback').load('check.php').show();

    $('#usernameID').keyup(function(){

        $.post('check.php',{username:registration.username.value},
        function(result){
            $('#usernameFeedback').html(result).show();
            var feedVar = $('#usernameFeedback').text();

        });
    });
});
</script>


<script>

$(document).ready(function(){
   $("#regForm").submit(function(){
     alert("HELLO"); // works fine
     if ( $('#usernameFeedback').text() == "Not available!" )
        return;
   event.preventDefault();
   });
});

</script>

使用此代码无法正常工作(我是 jquery 新手),如果用户名不可用,则不会停留在当前页面中。

4

2 回答 2

2

Pass the event to the function.

$("#regForm").submit(function(){

should be

$("#regForm").submit(function(event){

And use the return false in the same line as the if, since you are not using {}

Try this code:

$(document).ready(function () {
    $("#regForm").submit(function (event) {
        event.preventDefault();
        alert("HELLO"); // works fine
        if ($('#usernameFeedback').text() == "Not available!") {return false;}
    });
});
于 2013-10-09T19:36:50.997 回答
1

if()没有大括号的语句只会监听它下面的第一个也是唯一一个语句。如果包含大括号,则可以有多个语句,如下所示:

   if ( $('#usernameFeedback').text() == "Not available!" ) {
          event.preventDefault();
          return false;
      } else {
          return true;
      }

Furthermore, the event.preventDefault() won't ever execute with your current code, as the function is left before it's even able to execute, thus I've swapped those around, it's prevented by Default, then returned.

And Sergio quickly and rightly mentions, add event to function, to even allow you to event.preventdefault() in the first place!

于 2013-10-09T19:36:15.687 回答