为什么这个 javascript onkeypress 事件不起作用

Why this javascript onkeypress event doesn't work

当我在文本区域中添加文本时,此示例应该触发警报,出于某种原因,当我使用 $('#sentid1').onkeypress 时它会触发警报,并且它仅在我使用 $('#sentid1').onkeypress.[=15 时有效=]

html部分:

<div id="textarea" contenteditable=""><span id="sentid1" class="sentence"> This is sentence 1. </span><span id="sentid2" class="sentence"> This is sentence 2.</span></div>

Javascript/jQuery 部分:

 if (1==1) {
  $('#sentid1').onkeypress = function(event) {
            alert("theid: " + this.id);
        };  
  } else{
     document.onkeypress = function(event) {
              alert("theid: " + this.id);
           };   
  }

试试这个。 对于 jquery 选择器 $('#sentid1') 使用 jquery 按键

if (1==1) {
  $('#sentid1').keypress(function() {
            alert("theid: " + this.id);
        });  
  } else {
     document.keypress(function() {
              alert("theid: " + this.id);
        });   
  }
if (1==1) {
  $('#sentid1').Keypress(function(event) {
            alert("theid: " + this.id);
        });  
  } else{
     document.Keypress(function(event) {
              alert("theid: " + this.id);
           });   
  }

不清楚你的方法,如果你想在 textarea 上写一些东西,你可以使用 key up

if (1==1) {
  $('#sentid1').keyup(function(event) {
            alert("theid: " + this.id);
        });  
  } else{
     document.keyup(function(event) {
              alert("theid: " + this.id);
           });   
  }

您应该像这样附加事件处理程序

$(...).keypress(function(event) {...} )

$(...).on('keypress', function(event) {...} )

并且它需要附加到 #textarea,因为这是可以接受输入的元素,而 span 不能。

$('#textarea').keypress(function(event) {
  alert("theid: " + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textarea" contenteditable=""><span id="sentid1" class="sentence"> This is sentence 1. </span><span id="sentid2" class="sentence"> This is sentence 2.</span></div>


根据评论更新

如果要获取 span,请这样做,使用 event.target.id 获取 span

$('#textarea').keypress(function(event) {
  alert("theid: " + event.target.id);
});
#textarea {
  position: relative;
}
span[contenteditable] {
  outline: none;
}
span[contenteditable]:focus::before {
  content: '';
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  outline: 2px solid lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="textarea"><span contenteditable="" id="sentid1" class="sentence"> This is sentence 1. </span><span contenteditable="" id="sentid2" class="sentence"> This is sentence 2.</span></div>

您如何测试按键事件?为了触发按键事件,您需要您的元素是 focused 或者是触发按键的其他元素的父元素,因此按键是 bubbled.

您正在尝试在 span 上捕捉按键,默认情况下 span 不可聚焦,例如让我们使用 tabindex 来实现

<span id="sentid1" class="sentence" tabindex="0"> This is sentence 1. </span>

现在您实际上可以单击 在此跨度上,按一些键并查看预期结果