function createJSON() {
var data = new Object();
$("input[class = detail_text]").each(function() {
data[$(this).attr("name")] = $(this).val();
jsonString = JSON.stringify(data);
});
console.log(jsonString);
}
我试图在innerHTML中获取输入值。此输入字段是多值的。 如何获得这些属性?在我的代码中,最后一个是唯一获得保存的代码。我是新来的。感谢。
<div class="window task" style="left: 120px; top:200px; display:none;" data-nodetype="task" id="taskcontainer0">
<div class="ctrl_container">
<div class="button_remove">x</div>
</div>
<div class="details_container">
<label class="detail_label">Name</label>
<input type = "text" class="detail_text" name = "task"/><br/>
<label class = "detail_label">Description</label>
<input type = "text" class ="detail_text" name = "msg">
</div>
</div>
这是html代码。
答案 0 :(得分:3)
如果字段是多值的,您可能希望为每个名称存储数组,请参阅内联注释:
function createJSON() {
var data = {}; // {} is usually better than new Object
$("input[class = detail_text]").each(function() {
var $this = $(this),
name = $this.attr("name");
// Is there already a value saved for this name?
if (!data.hasOwnProperty(name)) {
// No, create a blank array
data[name] = [];
}
// Add this value to the array of values for this name
data[name].push($this.val());
});
jsonString = JSON.stringify(data);
console.log(jsonString);
}
另请注意,您可能打算在循环之后执行JSON.stringify
。
或者,如果你只想要一个数组 if ,你有给定name
的多个值,那么:
function createJSON() {
var data = {}; // {} is usually better than new Object
$("input[class = detail_text]").each(function() {
var $this = $(this),
name = $this.attr("name");
// Is there already a value saved for this name?
if (!data.hasOwnProperty(name)) {
// No, save this value
data[name] = $this.val();
}
else {
// Yes, is it an array?
if (!Array.isArray(data[name])) {
// No, make it one
data[name] = [data[name]]; // Wraps the existing value in an array
}
// Add this value to it
data[name].push($this.val());
}
});
jsonString = JSON.stringify(data);
console.log(jsonString);
}
Array.isArray
是一个ES5的东西,但垫片是微不足道的:
if (!Array.isArray) {
Array.isArray = (function() {
var toString = Object.prototype.toString;
return function(arg) {
return toString.call(arg) === "[object Array]";
};
})();
}
旁注:您几乎从不想使用属性选择器("input[class = detail_text]"
)来按类选择,因为当然元素可以有多个类。相反,请使用类选择器:"input.detail_text"