输入提交字段上的jquery事件

问题描述:

我有一个jQuery提交按钮onclick和默认事件的问题。 我想要做的是替换提交按钮上的点击事件,如果它有一个,并获得一个对话框显示,点击是对话框应该启动该默认onclick事件如果提交按钮有一个定义,如果它没有' t比默认事件应该发生(按钮提交表单),.submit()函数不适用于我在任何情况下,因为我需要通过一个表单发送此按钮,如果按钮没有点击.submit()发送表单数据无需提交数据。输入提交字段上的jquery事件

贝贝代码有一个问题,alert('xxx')总是被调用,它不应该,并在点击是按钮提醒和对话框创建再次被调用,如果我删除提醒按钮,我不能调用默认提交按钮事件(使用按钮提交表单)。

$('input.confirm').each(function(){ 
    var input = this; 
    var dialog = document.createElement("div"); 
    $(dialog).html('<p>AREYOUSHURE</p>'); 
    $(input).click(function(event) 
    { 
     event.preventDefault(); 
     var buttons = {}; 
     buttons['NO'] = function() { $(this).dialog("close"); }; 
     buttons['YES'] = function() { $(input).trigger('click'); $(this).dialog("close"); }; 

     $(dialog).dialog(
     { 
      autoOpen: false, 
      width: 200, 
      modal: true, 
      resizable: false, 
      buttons: buttons 
     }); 
     $(dialog).dialog('open'); 
     return false; 
    }); 
}); 

<form method="post" action=""> 
    <input type="hidden" value="1" name="eventId" /> 
    <input type="submit" value="Check" name="checkEvent" class="confirm" onclick="alert('xxx');" /> 
</form> 

当你添加一个onclick事件时,它将运行任何jQuery的独立。如果您正在使用jQuery进行混合,则不要使用onclick。

更好的解决方案:

var buttons = {}; 
var dialog = document.createElement("div"); 
$(dialog).html('<p>AREYOUSHURE</p>'); 
$('.confirm').click(function(event){ 
    event.preventDefault(); 
    var input = $(this); 
    buttons['NO'] = function() { $(this).dialog("close"); }; 
    buttons['YES'] = function() { $(input).trigger('click'); $(input).closest('form').submit(); $(this).dialog("close"); }; 

    $(dialog).dialog(
    { 
     autoOpen: false, 
     width: 200, 
     modal: true, 
     resizable: false, 
     buttons: buttons 
    }); 
    $(dialog).dialog('open'); 
    return false; 
}); 

全球范围的制作按钮。 然后当您单击是简单的提交表单

+1

这不会发送提交输入值与表单值,这是主要问题,我想要有与单击提交输入时相同的行为,它发送它的值与表单值,.submit()不做那。 – dfilkovi 2011-01-06 13:24:55

有可能通过合并on()off()方法(可使用jQuery 1.7+)来触发非默认的默认处理程序。我们的想法是:使用on()方法,它调用preventDefault()

  • 添加自定义处理程序;
  • 如果点击确认按钮,请在拨打trigger()之前使用off()删除自定义处理程序。

你的榜样看起来像如下:当点击NO按钮

$(function() { 
    var input = $('input.confirm'); 
    var dialog = document.createElement("div"); 

    $(dialog).html("<p>AREYOUSHURE</p>"); 
    $(dialog).dialog({ 
    autoOpen: false, 
    width: 200, 
    modal: true, 
    resizable: false, 
    buttons: { 
     "NO": function() { 
     $(this).dialog("close"); 
     }, 
     "YES": function() { 
     $(this).dialog("close"); 
     $(input).off("click", askConfirmation); 
     $(input).trigger("click"); 
     }, 
    } 
    }); 

    var askConfirmation = function (event) { 
    event.preventDefault(); 
    $(dialog).dialog("open"); 
    }; 

    $(input).on("click", askConfirmation); 
}); 

该代码会做什么,并会提交表单适当submit值是被点击时按钮。

另请注意,使用onclick属性与jQuery可能会导致意外的行为,即使您仅将它用于测试。我建议设置<form action="/some/unexistent/url">以检查是否触发了默认操作(如果确实如此,则会看到类似于404错误的内容;否则您将保持在同一页面上)。