带有.on('click')的event.preventDefault()不会阻止默认行为

时间:2014-03-28 10:03:14

标签: javascript jquery

我有以下HTML和javascript。当我点击具有链接的.todo.completedmsg时,我期待event.preventDefault()。但它跳到了链接。

$("#form").on('click',".todo", function(event){...}
$("#form").on('click','.completedmsg', function(event){...}

我在这里做错了什么?

HTML全部

<div id="homeright" class="adminhome">
    <form method="post" id="form" action="admin/insertShoutBox">
        <input type="hidden" name="user_id" id="user_id" value="1">
        <input type="hidden" name="user" id="nick" value="admin">
        <p class="messagelabel"><label class="messagelabel">Message</label>
            <textarea id="message" name="message" rows="2" cols="80"></textarea>
        </p>
        <div class="buttons">
            <button type="submit" class="positive" name="submit" value="submit">
            <img src="http://localhost/website2014/assets/icons/disk.png" alt="disk">            Save            </button>
        </div>
    </form>
    <div id="loading" style="display: none;"><img src="../../assets/images/general/ajax-loader2.gif" alt="Loading now. Smile"></div>
    <div class="clearboth"></div>
    <div id="container">
        <span class="clear"></span>
        <div class="content">
            <h1>Latest Messages or Task To Do</h1>
            <ul id="message_ul" style="display: block;">
<li class="1">
<div class="listbox"><span class="user"><strong>admin</strong></span>

<span class="date">2014-03-28 17:25:50</span>
<a href="http://localhost/website2014/index.php/messages/admin/changestatus/1" class="todo">to do</a><span class="msg">test</span></div></li></ul>   
        </div>
    </div>
    <div id="completed">
        <h1>Completed Lists</h1>
        <ul id="completed_ul" style="display: block;">
<li class="2">
<span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 18:11:29</span>
<a href="http://localhost/website2014/index.php/messages/admin/changestatus/2" class="completedmsg">completed</a>
<a href="http://localhost/website2014/index.php/messages/admin/delete/2" id="2" class="delete">x</a><span class="msg">another test
</span>
</li></ul>
    </div>
</div>

jQuery all

$(document).ready(function(){
  //global vars
  var inputUser = $("#nick");
  var inputMessage = $("#message");
  var loading = $("#loading");
  var messageList = $("#message_ul");
  var completedmsg = $("#completed");
  var completedList = $("#completed_ul");
  //Load for the first time the shoutbox data
  updateShoutbox();
  updateCompletedbox();

  function updateShoutbox()
  {    
    //just for the fade effect
    messageList.hide();
    loading.fadeIn();
    //send the post to shoutbox.php
    $.ajax({
      type: "POST", 
        url: "<?php echo site_url('messages/admin/AjaxgetShoutBox'); ?>", 
        complete: function(data)
  {
    loading.fadeOut();
    messageList.html(data.responseText);
    messageList.fadeIn(500);
    //completedList.fadeIn(500);
  }
    });
  }



  function updateCompletedbox()
  {
    //just for the fade effect
    completedList.hide();
    loading.fadeIn();
    //send the post to shoutbox.php
    $.ajax({
      type: "POST", 
        url: "<?php echo site_url('messages/admin/AjaxgetCompletedBox'); ?>", 
        complete: function(data)
  {
    loading.fadeOut();
    completedList.html(data.responseText);
    // messageList.fadeIn(500);
    completedList.fadeIn(500);
  }
    });
  }


  //check if all fields are filled
  function checkForm()
  {
    if(inputUser.val() && inputMessage.val())
    {
      return true;
    }   
    else
    {
      return false;
    }

  }


  //on submit event
  $("#form").submit(function(event){
    event.preventDefault();
    if(checkForm())
    {
      var nick = inputUser.attr("value");
      var message = inputMessage.attr("value");
      //we deactivate submit button while sending
      $("#send").attr({ disabled:true, value:"Sending..." });
      $("#send").blur();
      //send the post to shoutbox.php
      $.ajax({
        type: "POST", 
          url: "<?php echo site_url('messages/admin/insertShoutBox'); ?>", 
          data: $('#form').serialize(),
                complete: function(data)
    {
      messageList.html(data.responseText);
      updateShoutbox();
      $('#message').val('');
      //reactivate the send button
      $("#send").attr({ disabled:false, value:"SUBMIT !" });
    }
      });
    }
    else alert("Please fill all fields!");
    //we prevent the refresh of the page after submitting the form
    return false;
  });

  //on todo event. this changes the status to compeleted

  $("#form").on('click',".todo", function(event){
    event.preventDefault();
    loading.fadeIn();
    var href = $(this).attr("href");
    var msgContainer = $(this).closest('li');
    $.ajax({
      type: "POST",
        url: href,
        cache: false,
        complete: function()
        {
        msgContainer.slideUp('slow', function() {$(this).remove();});
        updateShoutbox();
        updateCompletedbox();
        loading.fadeOut();
        }
    });     
  });


  // on complete event. this changes the status to todo
  $("#form").on('click','.completedmsg', function(event){
    event.preventDefault();
    loading.fadeIn();
    var href = $(this).attr("href");
    var CompMsgContainer = $(this).closest('li');
    $.ajax({
      type: "POST",
        url: href,
        cache: false,
        complete: function(){
          CompMsgContainer.slideUp('slow', function() {$(this).remove();});
          updateShoutbox();
          updateCompletedbox();
          loading.fadeOut();
        }
    });
  });  



  $("#form").on('click','.delete',function(event){
    event.preventDefault();
    // alert ('clicked');
    loading.fadeIn();
    var href = $(this).attr("href");
    var commentContainer = $(this).parent();
    var id = $(this).attr("id");
    $.ajax({
      type: "POST",
        url: href,
        cache: false,
        complete: function()
    {    
      commentContainer.slideUp('slow', function() {$(this).remove();});
      updateShoutbox();
      updateCompletedbox();
      loading.fadeOut();
    }
    });
  });
});

1 个答案:

答案 0 :(得分:1)

#form内部没有todo类的链接 - 因此事件未附加到您的链接:

  

.on()方法将事件处理程序附加到jQuery对象中当前选定的元素集。

链接位于表单之外,因此无法触发这些特定事件。如果事件没有触发,那么链接被“跳转”是有意义的,因为没有什么可以捕获它。如果您在表单中放置了.todo 类的链接,您将获得所需的效果。

作为第一个测试,您可以绑定到$(document)而不是#form并在重新处理HTML之前检查preventDefault,以便您可以绑定到DOM中的较低级别元素(如果需要......)

问题的简要示例:http://jsfiddle.net/YWV9A/1/

解决方案:http://jsfiddle.net/YWV9A/3/