我有一个简单的表单,有4个输入,我需要动态添加占位符。
我想我理解json的一般想法,但我不确定如何使这项工作。有人可以帮助我吗?
var inputArray = [
{"inputClass":"name","placeholder":"Your Name*"},
{"inputClass":"phone","placeholder":"Your Phone*"},
{"inputClass":"email","placeholder":"Your Email*"},
{"inputClass":"message","placeholder":"Your Message*"}
];
$.each(inputArray, function(i, inputClass, placeholder) {
$('form').find('input.'+inputArray[i].inputClass).attr("placeholder", inputArray[i].placeholder);
});
答案 0 :(得分:0)
您的代码没有任何问题,除了.each(...)
回调的签名有点不对。它应该是function(index,element) { ... }
。但无论如何,你的代码仍然有效更清晰的编写代码的方法是:
var inputArray = [
{"inputClass":"name","placeholder":"Your Name*"},
{"inputClass":"phone","placeholder":"Your Phone*"},
{"inputClass":"email","placeholder":"Your Email*"},
{"inputClass":"message","placeholder":"Your Message*"}
];
$.each(inputArray, function(i, item) {
$('form').find('input.'+item.inputClass).attr("placeholder", item.placeholder);
});