jQuery 中的第 3 次按键不会触发按键功能

keypress won't trigger function on 3rd press in jQuery

我正在尝试使用带有按键事件处理程序的回车键将一个图像更改为另一个图像。该功能被触发并将图像更改为另一个很好,并且在另一个按键(再次输入)上返回到原始图像也很好,但是当我第三次尝试更改它时它什么也没做。这意味着当我再次尝试更改原始图像时,它什么也没做。 我曾尝试将 keypress 更改为 keydown 并且也徒劳地使用了 off 功能。谁能告诉我这里出了什么问题:

    <script>
        $(".logoheader").on("keypress",function(e) {
            if(e.which == 13 || e.which == 32){
                $(".logoheader").html("SKATE <img class='secondImage' src='./thought.png' align='center' width='100px' alt='logo image' /> STATE");
                

                $(".logoheader").on("keypress", function() {
                    $(".logoheader").html("SK8 <img class='logoImage' src='./head.png' align='center' width='100px' alt='logo image' /> ST8");
                    $(".logoheader").off("keypress");
                    })
                }});
        function logoShift(){
                $(".logoheader").html("SKATE <img class='secondImage' src='./thought.png' align='center' width='100px' alt='logo image' /> STATE");
                

                $(".logoheader").click(function() {
                    $(".logoheader").html("SK8 <img class='logoImage' src='./head.png' align='center' width='100px' alt='logo image' /> ST8");
                    $(".logoheader").off("click");

            });};
    </script>
    <html>
        <h1 class="logoheader" align="center" onclick="logoShift()" tabindex=0> SK8 <img class="logoImage" src="./head.png" align="center" width="100px" alt="head" /> ST8</h1>
    </html>

如您所见,我有一个点击功能 (logoShift),工作正常,我什至尝试在按键时触发它,但也是徒劳(它只在第一次点击时有效,而不会返回到原始图像在第二次按键时)

只需在文档就绪时绑定事件并检查类名:

$(function() {
    $(".logoheader").on("keypress", function(e) {
   if (e.which == 13 || e.which == 32) {
     if ($(this).find('img').hasClass('logoImage')) {
       $(this).html("SKATE <img class='secondImage' src='https://brand.jquery.org/resources/jquery-mark-light.gif' align='center' width='100px' alt='logo image' /> STATE");
     } else {
       $(this).html("SK8 <img class='logoImage' src='https://brand.jquery.org/resources/jquery-mark-dark.gif' align='center' width='100px' alt='logo image' /> ST8");
     }

   }
 });

 $(".logoheader").click(function() {
   if ($(this).find('img').hasClass('logoImage')) {
     $(this).html("SKATE <img class='secondImage' src='https://brand.jquery.org/resources/jquery-mark-light.gif' align='center' width='100px' alt='logo image' /> STATE");
   } else {
     $(this).html("SK8 <img class='logoImage' src='https://brand.jquery.org/resources/jquery-mark-dark.gif' align='center' width='100px' alt='logo image' /> ST8");
   }

 });
});

https://jsfiddle.net/agy0jw58/