javascript - 在输入值之前添加主题标签
问题描述
我把它作为输入标签的一部分:
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 代码中。
解决方案
这是一个例子
<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>
推荐阅读
- ruby-on-rails - 没有路由匹配 {:action=>"show", :controller=>"events", :id=>nil},缺少必需的键:[:id]
- java - 线程“主”java.lang.NoClassDefFoundError 中的异常:org/junit/platform/commons/util/ClassNamePatternFilterUtils
- apache-kafka - 在 Spring Cloud Kafka Streams 中序列化/反序列化泛型类型
- php - Angular 和 XAMPP CORS 政策
- python - VSCode:排序导入与组织导入
- javascript - 如何将字符串变量传递给匿名 Adobe View SDK 脚本?
- css - 如何更改 Angular Material 对话框容器宽度大小
- javascript - 使用 Array.from 时如何设置/定义 var 类型?
- sql - 如何使用 SQL Server 使用它们所在的多边形的 ID 填充点表中的字段?
- reactjs - 如何在草稿 js 中创建自定义键绑定(Ctrl+Enter)