在Internet Explorer中未触发jQuery单击事件

时间:2012-08-31 16:18:45

标签: jquery internet-explorer

当用户在文本框中按Enter键时,我正尝试通过jquery按钮点击事件提交表单。

以下是我的代码

<script>
    $(function() {
       $('.buttonComment').live("click", function(e) {
          alert('er');
       });
     });​
</script>

<form>
<input type="text" class="inputComment" id="inputComment<?php echo $msg_id;?>" value=""/>
<input type="submit" class="buttonComment" id="<?php echo $msg_id;?>" value='' />
<i id="iComment<?php echo $msg_id;?>"/>
</form>

以上代码在Firefox中运行良好。但是使用Internet Explorer,它无法触发按钮单击事件。而是提交表格。

当我点击提交按钮时,它可以正常工作。但是当我按下文本框中的光标时输入,它无法正常工作。

总之,我正试图像Facebook一样实现评论系统。

Here is jsFiddle example

2 个答案:

答案 0 :(得分:0)

我最近偶然发现了这个!我无法相信它发生了 - 因为帖子数据正确传递了!

没有合理的解释,现在我必须说这只是Internet Explorer未被注意的错误!

解决方案1 ​​

Internet Explorer似乎在加载时扫描页面并确定哪些提交按钮可见,然后将输入提交功能附加到这些表单。

要修复此方案,您可以使用以下jQuery代码:

$(document).ready(function() {
   $('input').keydown(function(e){
     if (e.keyCode == 13) {
        $(this).parents('form').submit();
        return false;
     }
   });
}); 

返回false在Internet Explorer中非常重要,因为它会阻止您在返回时听到的哔声。嘟嘟声说“你不能在这里输入!”,但是返回false会取消按键,因此浏览器不会发出警告。

详细了解此内容以及人们的评论:Submit a Form in IE with Enter

解决方案2

另一个解决方案可能是但在我的情况下它不起作用是添加额外的隐藏输入字段:

<!-- Fix for Internet Explorer bug (One text input and submit, disables submit on pressing "Enter") -->
  <div style="display:none">
    <input type="text" name="hiddenText"/>
  </div>

解决方案3

另一种解决方案是检测用户的浏览器,如果是Internet Explorer取消输入密钥并强制用户点击提交按钮进行正确的提交。

function browserIE(){
   if($.browser.msie && parseInt($.browser.version) <= 8){   // Let's detect if it's Internet Explorer 8 or lower
     return true;
 }
  return false;

}

$(document).keypress(function(event) { // Bind keyboard events
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13' && browserIE()){ // When user hits 'enter key' (keyCode 13) and only when the browser is Internet Explorer version 8 or lower
            event.preventDefault();
            event.stopPropagation();
        }
});

这是强制Internet Explorer用户单击“提交”按钮以执行正确提交的唯一方法,因为,正如我之前提到的那样,在场上点击输入将无法正确提交,并且最终会以简单的页面重新加载结束!

jsFiddle Working Example

同时推荐阅读:Button versus Input[type="submit"] in Internet Explorer and beyond

答案 1 :(得分:0)

确保按钮有type="submit"。你必须在IE中提到这一点;在Chrome和Firefox中,这似乎是默认类型。

我正在使用它,它无处不在。尝试使用表单提交处理程序而不是单击:

<form id="1234">
    <input type="text" />
    <button type="submit" id="asdasd" >Button </button>
</form>

<script>
   $("#1234").submit(function(){
      alert("Hello World");
   })
</script>