添加焦点功能并在模糊时删除它

发布于 2025-01-19 16:46:45 字数 1308 浏览 1 评论 0原文

我试图设置一个简单的脚本,每当您专注于输入并按Enter时,都会发生一些事情。就像在网页和论坛上的搜索框中一样。

问题是我无法在用户单击其他位置点击之后停止功能。 我尝试添加模糊,这无济于事,我得到了

“未介绍的参考:prestenter尚未定义 htmlinputelement。”

还试图将该函数设置为一个函数,并在EventListener中稍后调用它,但我无法通过事件参数来使用该函数以使该功能起作用(我刚刚开始研究EventListeners我)

感谢您对如何正确参考prestenter函数或任何不同解决方案的任何帮助。

inputTest = document.querySelector("#test")


inputTest.addEventListener("focus", function pressEnter() {


    window.addEventListener("keyup", (e) => {
        if (e.key === "Enter") {
            console.log("Pressed")
        }
    })
})

inputTest.addEventListener("blur", () => {

    window.removeEventListener("keyup", pressEnter())
    console.log("Done(?)")

}
)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
</head>

<body>
    <input type="text" id="test">

    <script src="script.js"></script>
</body>

</html>

I'm trying to set a simple script where, whenever you focus on an input and press Enter, something happens. Just like in those searchboxes on webpages and forums.

The problem is I can't make the function stop after the user clicks in a different place.
I tried adding blur and it doesn't help, I get a

"Uncaught ReferenceError: pressEnter is not defined at
HTMLInputElement."

Also tried to set the function as an individual one and call it later in the eventlistener BUT I can't pass the event argument for that function to work (I've just started studying EventListeners so, please, take it easy on me)

I'd appreciate any help on how to correctly reference the pressEnter function or any different solutions.

inputTest = document.querySelector("#test")


inputTest.addEventListener("focus", function pressEnter() {


    window.addEventListener("keyup", (e) => {
        if (e.key === "Enter") {
            console.log("Pressed")
        }
    })
})

inputTest.addEventListener("blur", () => {

    window.removeEventListener("keyup", pressEnter())
    console.log("Done(?)")

}
)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
</head>

<body>
    <input type="text" id="test">

    <script src="script.js"></script>
</body>

</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

晨曦÷微暖 2025-01-26 16:46:45

您不需要如此复杂的“体系结构”即可实现该功能,您只需要将事件侦听器直接添加到input element,例如:

const inputTest = document.querySelector("#test")

inputTest.addEventListener("keyup", (e) => {
    if (e.key === "Enter") {
        console.log("Pressed")
    }
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
</head>

<body>
    <input type="text" id="test">

    <script src="script.js"></script>
</body>

</html>

You don't need such a complicated "architecture" to achieve that functionality, you need just to add the keyup event listener directly to input element, like so:

const inputTest = document.querySelector("#test")

inputTest.addEventListener("keyup", (e) => {
    if (e.key === "Enter") {
        console.log("Pressed")
    }
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
</head>

<body>
    <input type="text" id="test">

    <script src="script.js"></script>
</body>

</html>

悲念泪 2025-01-26 16:46:45

根据您想要做的事情,您可以用表单标签替换事件侦听器。如果您试图实现诸如搜索栏之类的内容,这可能在语义上是正确的。看看这是否对您有用:

const handleSubmit = () => {
  const input = document.querySelector("#test");
  const inputValue = input.value;

  console.log(inputValue);

  // You can handle any logic here

  return false;
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Events</title>
  </head>

  <body>
    <form name="eventForm" onsubmit="handleSubmit()" action="#">
      <input type="text" id="test" />
    </form>

    <script src="script.js"></script>
  </body>
</html>

Based on what you are trying to do you could replace your event listener with a form tag. If you are trying to implement something like a search bar this could be semantically correct. See if this works for you:

const handleSubmit = () => {
  const input = document.querySelector("#test");
  const inputValue = input.value;

  console.log(inputValue);

  // You can handle any logic here

  return false;
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Events</title>
  </head>

  <body>
    <form name="eventForm" onsubmit="handleSubmit()" action="#">
      <input type="text" id="test" />
    </form>

    <script src="script.js"></script>
  </body>
</html>

丑疤怪 2025-01-26 16:46:45

网页和论坛上的搜索框只是检测当前 DOM 上的按键操作。像下面这样。

// EnterkeyListener
  document.addEventListener('keyup' , function(e){

  if (e.key == "Enter") {
      const searchValue = document.querySelector("#test").value;
      console.log(searchValue);
  };
  });

如果你真的希望搜索栏为空时什么都不会发生,那么你可以使用 if 语句,例如

    // EnterkeyListener
    document.addEventListener('keyup' , function(e){
    
      if (e.key == "Enter") {
          const searchValue = document.querySelector("#test").value;
   // check if searchbar has any value if so then run this code
          if (searchValue) {
            console.log("I have a value")  
            console.log(searchValue);
          } else {   //if not then run this code
            console.log("i don not have a value");
            console.log(searchValue);
          };
      };
      });

Searchboxes on webpages and forums simply detect a keyup on the current DOM. like the following.

// EnterkeyListener
  document.addEventListener('keyup' , function(e){

  if (e.key == "Enter") {
      const searchValue = document.querySelector("#test").value;
      console.log(searchValue);
  };
  });

and if you really want nothing should happen when the searchbar is empty then you can use a if statement like

    // EnterkeyListener
    document.addEventListener('keyup' , function(e){
    
      if (e.key == "Enter") {
          const searchValue = document.querySelector("#test").value;
   // check if searchbar has any value if so then run this code
          if (searchValue) {
            console.log("I have a value")  
            console.log(searchValue);
          } else {   //if not then run this code
            console.log("i don not have a value");
            console.log(searchValue);
          };
      };
      });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文