使用 jQuery 在 div 中按下的输入执行操作



有一些类似的线程,我已经检查和测试过了。但不要为我的情况工作。

我有评论框,我想在用户按Enter键时发表评论。

<div contenteditable="true" class="commentMark" id="commentMark-<?php  echo $row['p_id'];?>" onblur="if (this.value=='') this.value = 'Write a comment'" onfocus="if (this.value=='Write a comment') this.value = ''" onKeyPress="return SubmitComment(this,event)" wrap="hard" name="commentMark" style=" background-color:#fff; overflow: hidden;">Write a comment</div>

脚本:

$(function(){
 $('.commentMark').keypress(function (e) {
    if (e.keyCode == 13) {
        alert('You pressed enter!');
    }
 });
});
// $("$commentMark").keypress(function (e) ..

也不执行任何操作。

这是怎么回事?

更新我还检查了小提琴是否有效。但是不知道我的本地主机出了什么问题。它看起来像。

墙.php

<script type="text/javascript">
$(function(){
 $('.commentMark').keypress(function (e) {
    if (e.keyCode == 13) {
        alert('You pressed enter!');
    }
 });
});
</script>
<?php
<div contenteditable="true" class="commentMark" id="commentMark-<?php  echo $row['p_id'];?>" onblur="if (this.value=='') this.value = 'Write a comment'" onfocus="if (this.value=='Write a comment') this.value = ''" onKeyPress="return SubmitComment(this,event)" wrap="hard" name="commentMark" style=" background-color:#fff; overflow: hidden;">Write a comment</div>
?>

现在有什么问题吗? 因为它仍然无法在我的本地主机上工作。

请确保您已包含jQuery库。我已经检查了代码及其工作。您可以在此处查看。

JSFiddle

你的代码运行良好,只有一个问题,你确定在你的代码中使用吗

$('.commentMark').keypress(function (e) {

因为我也可以看到另一行代码

// $("$commentMark").keypress(function (e) ..

甚至它有评论,但请确保它没有被使用。因为$不在选择器中使用! .#的使用类似于 CSS。

编辑

使用这个:

<div onkeydown="alrtme()"></div>
嘿,根据需要

编写所有其他属性,但只需更新div 中的 onkeydown。

然后将函数更新为

function alrtme(){
  if (e.keyCode == 13) {
    alert('You pressed enter!');
  }
});

这是一个简单的,当div 上有keydown事件时会运行。并且会运行,如果输入密钥,则会出现警报!

编辑小提琴中的错误:

打算编辑小提琴,然后我想我应该找一个return,猜猜我发现了什么,

function SubmitComment(myfield,e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
}
else
return true;
}

这是最后一个,SubmitComment是按下按键时的功能。在那里,您已将回车键设置为无或假。在那里更改它并将其写成:

function SubmitComment(myfield){
  if (event.keyCode == 13){
      /* 
       * you don't need to use the keycode variable, just use them as this..
       * and then submit it ..
       */ 
  }
else
return true;
}

祝你好运!

最新更新