繁体   English   中英

event.preventDefault()不适用于jquery.trigger(“ click”)

[英]event.preventDefault() not being honored for a jquery.trigger(“click”)

我页面上的form内有复选框:

<form id="oneform" action="blah..">
    <input type="checkbox" name="checkboxes" id="chkbox1"/>Checkbox1
    <input type="checkbox" name="checkboxes" id="chkbox2"/>Checkbox2
...

注意 :选中/取消选中任何复选框时,都会提交此表单。 这是jQuery代码:

$("input[name='checkboxes']").bind("click",function(e) {
    e.preventDefault(); 
    ....

    $("#oneform").submit();
});

上面函数中e.preventDefault()的作用是:如果选中了该复选框并单击了该复选框,则阻止默认将确保它保持选中状态,以便浏览器在提交表单之前记录复选框状态。 因此,在提交表单后,该复选框将按预期取消选中,在“返回”按钮上,我将再次看到该复选框被选中。 这对我有效

然后,我在该表单上显示了一个div,该div显示了显示已选中复选框名称的元素列表。

<div>
  <% This is a JSTL code: for each element  %>
      <a class="close-tag" href="#" value="<% JSTL put the checkbox id %>"><span><% jSTL put checkbox name</span> X</a>
  <% end %>
</div>

如果单击“ X”,则有一个jQuery处理程序,如下所示:

$(".close-tag").bind('click', function(e) {
 e.preventDefault() // again for same reasons as mentioned above

// get the name of checkbox id from event target
.....
 var selector = ... // checkbox id 

// fake the checkbox clicking event
$("#"+selector).trigger("click");
// doing the above goes to the above jquery snippet as you would expect.

// the checkbox also remains checked as expected due to e.preventDefault()
// However on server side it should send the checkbox as "unchecked" instead it sends as  checked

});

我想念任何东西吗? 它不适用于FF,Chrome浏览器感谢您的指导!

通过用香草JS替代品替换$(selector).trigger()进行更新document.getElementById(selector).click() ...我能够解决此问题。 可以在FF,IE8 / 9,Safari,Chrome,Opera上正常工作!

更新:

实际上,我错过了一些非常明显的事情。 调用trigger()您需要指定要触发的事件,因此需要将其设为trigger('click')


如果我正确阅读它,则表示它仍显示为选中状态,但希望它向服务器报告为未选中状态。

那是不可能的。 一个元素没有两个这样的状态,只有一个。

但是,您可以做的是将复选框更改为未选中,提交表单,然后再次将其标记为已选中。

暂无
暂无

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

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