今天打开电脑,朋友说帮忙解决个bug
实现input1框输入文字,input2显示input1的val();
心想呀这还不简单,不就是获取1的val()然后赋值给2不就ok了吗?有难度?瞬间怀疑他的水平是不是倒退了
然而
并没有那么简单
要达到的效果是:通过ajax数据请求,input1中输入data数据中的key值,input2显示对应的value值
data数据:
{
"shop1":"iphone7",
"shop2":"华为",
"shop3":"小米",
"shop4":"三星",
"shop5":"oppo"
}
结构:
<div class="box">
<input type="text" class="input1" placeholder="编号">
<input type="text" class="input2" placeholder="名称">
</div>
$(".input1").blur(function () {
var input = $(".input1").val();
$.ajax({
url:'data/tsconfig.json',
type:'get',
dataType:'json',
success:function(res){
console.log(res);
console.log("input="+input);
console.log(res.input);
console.log(res.shop1);
$(".input2").val(res.input);
},
error:function () {
console.log(error);
}
});
});
但是遇到了问题:
console.log(res.input); 显示为undefined
当然啦,肯定会有解决方案的
废话不多说,直接上代码:
success:function(res){
var input = $(".input1").val();
for(key in res){
if(input == key){
$(".input2").val(res[key]);
}
}
},
通过判断input1的val()是不是等于data数据中的key,然后赋值给input2的val();
最佳解决方案:
$(".input2").val(res[input]);
是不是豁然开朗了呢
最终效果图: