0

我有一个带有 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);
});​
4

1 回答 1

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);
});​

工作小提琴:http: //jsfiddle.net/RQAJA/

于 2012-08-06T06:10:08.923 回答