如何在一个input输入框绑定一个动态id值
1、首先创建html元素<div class="dynamicId">
<span>点击按钮设置指定id的文本的值:</span>
<div class="contents">
<input type="text" id="test1" value="我的id是test1">
<input type="text" id="test2" value="我的id是test2">
<input type="text" id="test3" value="我的id是test3">
</div>
设置id等于 <input type="text" name="target-id">的文本框的值为 <input type="text" name="new-value">
<input type="button" value="设置">
</div>
2、再设置CSS样式:
div.dynamicId{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;}
div.dynamicId span{color:#999;font-style:italic;}
div.contents{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;}
table{border-collapse:collapse;}
td{width:30px;height:30px;line-height:30px;text-align:center;border:1px solid green;}
.selected{background:#99ccff;}
input[type='button']{height:30px;margin:10px;padding:5px 10px;}
input[type='text']{width:200px;height:35px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;}
3、编写主要js代码
$(function(){
$(":button").click(function() {
var id = $("input[name='target-id']").val(); // 首先动态获取id
var value= $("input[name='new-value']").val(); // 获取新设置值
$("input#"+id).val(value);
});
})
4、代码编写完成后运行该例子
5、在第一个框中输入id: test2 ,在第二个框中输入 我被改变了 。