html 文字自动转大写

最近工作中项目有一个小需求,要将用户输入的内容自动转成大写的,用到了离焦 .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>

效果如图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值