首页 > 解决方案 > 在输入值之前添加主题标签

问题描述

我把它作为输入标签的一部分:

onkeyup = "this.value = '#' + this.value;"

它为每个字母添加了一个标签。我只想要 1 个标签。

我也试过这个:

onkeyup = "if (this.charAt(0) != '#') this.value = '#' + this.value;"

还有这个:

onkeyup = "if (this.charAt(0) != '#') this.value = '#' + this.value; return this.value"

我知道理想情况下您希望将脚本放在单独的 .js 文件中,但这只是一个非常小的项目,我只想将其放入 html 代码中。

标签: javascript

解决方案


这是一个例子

<input onkeyup="if (this.value[0] !== '#') this.value = '#' + this.value"></input>

问题是你需要做this.value.charAt(0)还是this.value[0]不做this.charAt(0)

希望这会有所帮助。

编辑:正如@epascarello 建议的那样,您也可以使用该onchange事件,这样它就不会在您键入时移动光标。

<input onchange="if (this.value[0] !== '#') this.value = '#' + this.value"></input>


推荐阅读