最近工作中项目有一个小需求,要将用户输入的内容自动转成大写的,用到了离焦 .blur 的方法,项目代码不方便贴上来,写了个极简版本,代码如下:
<body>
<script type="text/javascript" src="jquery-2.1.1.min.js">
</script>
<script type="text/javascript">
$(function() {
$("input[type='search']").on("blur",function(){
this.value=this.value.toUpperCase();
});
});
</script>
<label>test</label>
<input type="search" id="test" name="test" />
</body>
效果大致如下:
移开焦点之后自动变成大写
但是项目上有些需求,要添加上一些input框,这时发现自动变大写的功能无法实现。
大致代码如下
<body>
<script type="text/javascript" src="jquery-2.1.1.min.js">
</script>
<script type="text/javascript">
$(function() {
$("input[type='search']").on("blur",function(){
this.value=this.value.toUpperCase();
});
$("#add").click(function(){
var param = "<label>test1</label>"+"<input type='search' id='test1' name='test1'/>";
document.getElementById("mainarea").innerHTML = param;
});
});
</script>
<div>
<label>test</label>
<input type="search" id="test" name="test" />
<button type="button" id="add">添加一个input</button>
</div>
<div id="mainarea">
</div>
</body>
效果如图
如图所示,下面动态添加的input无法达到离焦大写的功能,根据查询:应该是因为异步导致绑定事件失败,需要全局绑定
参考链接如下
https://blog.csdn.net/u011415782/article/details/89230040
https://blog.csdn.net/qq_34117170/article/details/76130868
通过以上两个链接的启示,修改代码如下
<body>
<script type="text/javascript" src="jquery-2.1.1.min.js">
</script>
<script type="text/javascript">
$(function() {
// 全局绑定,经测试有效
$("body").on("blur","input[type='search']",function(){
this.value=this.value.toUpperCase();
});
// 此种绑定无效
// $("input[type='search']").on("blur",function(){
// this.value=this.value.toUpperCase();
// });
$("#add").click(function(){
var param = "<label>test1</label>"+"<input type='search' id='test1' name='test1'/>";
document.getElementById("mainarea").innerHTML = param;
});
});
</script>
<div>
<label>test</label>
<input type="search" id="test" name="test" />
<button type="button" id="add">添加一个input</button>
</div>
<div id="mainarea">
</div>
</body>
效果如图