尝试单击模糊后更改文本框中的文本

时间:2019-04-05 12:14:20

标签: javascript blur dom-events

很抱歉,这个问题太简单了。我正在尝试使用事件处理程序&and的所有实例更改为blur。即使我的功能仅仅是

,我似乎也看不到模糊的变化

id.value = "Random test string";

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

我已注释掉用于更改&的代码,因为我正在检查与模糊事件处理程序关联的函数是否完全在触发,而实际上没有。此代码还包含一个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>

2 个答案:

答案 0 :(得分: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>

我希望这会有所帮助。

答案 1 :(得分: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