简体   繁体   English

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

[英]event.preventDefault() with .on('click') doesn't prevent default behavior

I have the following HTML and javascript. 我有以下HTML和javascript。 When I click .todo and .completedmsg which have links, I am expecting event.preventDefault(). 当我点击.todo.completedmsg其中有联系,我期待event.preventDefault()。 But it jumps to the link. 但它跳到链接。

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

What am I doing wrong here? 我在这里做错了什么?

HTML all 全部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 jQuery全部

$(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();
    }
    });
  });
});

There are no links inside #form with a class of todo - so the events are not attached to your links: #form中没有todo类的链接-因此事件未附加到您的链接中:

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. .on()方法将事件处理程序附加到jQuery对象中当前选定的元素

The links are outside of the form, so those particular events can't be firing. 链接不在表单之外,因此无法触发这些特定事件。 If the event isn't firing then it makes sense that the links are being 'jumped to' as there's nothing to trap it. 如果事件未触发,则说明链接被“跳转至”是有意义的,因为没有任何陷阱可以捕获。 If you place a link with the class of .todo inside the form, you will get the desired effect. 如果将与类的链接.todo形式里面 ,你会得到预期的效果。

As a first test, you could just bind to $(document) instead of #form and check the preventDefault before re-working the HTML so that you can bind to a lower-level element in the DOM (if required...) 作为第一个测试,您可以绑定到$(document)而不是#form并在重新处理HTML之前检查preventDefault,以便可以绑定到DOM中的较低级元素(如果需要...)

Cut-down example of issue: http://jsfiddle.net/YWV9A/1/ 问题的缩小示例: http : //jsfiddle.net/YWV9A/1/

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

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

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