尝试使用模糊点击文本框中的文本

问题描述 投票:0回答:2

如果这个问题太简单,我很抱歉。我试图使用事件处理程序&and的所有实例更改为blur。即使我的功能很简单,我似乎也没有对模糊进行任何改变

id.value = "Random test string";

所以我假设这是事件处理程序本身的问题。任何帮助将不胜感激,谢谢。

我有更改&的代码注释掉了,因为我正在检查与blur eventhandler绑定的函数是否完全触发,但事实并非如此。此代码还有一个HTML文件,其文本框的ID为textid

 <script type="text/javascript">
    //var for saving the string
    var textvar;
    //var for the texta area
    var id = document.getElementById("textid");
    id.addEventListener("blur", function() {

        //textvar = id.value;
        //textvar = textvar.replace("&", " and ");
        //id.value = textvar;

        textvar = "Correct!!";
        id.value = textvar;

    }, false);
 </script>
javascript blur dom-events
2个回答
0
投票

此代码正常工作并且符合预期:

<input type="text" id="textid" />

JS代码

//var for saving the string
var textvar;
//var for the texta area
var id = document.getElementById("textid");

id.addEventListener("blur", function() {
    textvar = id.value;
    textvar = textvar.replace(/\&/g, " and ");
    id.value = textvar;
}, false);

你可以在这里找到工作的Pen


0
投票

您可能想要考虑另一种方法:

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">
  function change(element) {
    let textvar = element.value;
    if (textvar.indexOf('&') !== -1) {
      textvar = textvar.replace("&", " and ");
    }
    element.value = textvar;
  }
</script>
</head>

<body>
    <input type="text" onblur="change(this)" />
</body>
</html>

我希望这可以有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.