gpt4 book ai didi

javascript - 从 json 中查找元素

转载 作者:行者123 更新时间:2023-11-30 06:32:04 25 4
gpt4 key购买 nike

<h3>Customer</h3>
<dl>
<dd>
<input name="customer[customerId]">
</dd>
<dt>customer[customerName]</dt>
<dd>

<input name="customer[customerName]">
<span class="error">Find me</span>
</dd>
</dl>

<h3>Address</h3>

<dl>
<dd>
<input name="customer[address][addressId]">
</dd>
<dd>
<input name="customer[address][address1]">
</dd>
<dd>
<input name="customer[address][address2]">
</dd>
<dt>customer[address][address3]</dt>
<dd>
<input name="customer[address][address3]">
<span class="error">Find me</span>
</dd>
</dl>

<h3>District</h3>
<dl>
<dt>customer[district][districtId]</dt>
<dd>
<select name="customer[district][districtId]"><br>
<option value="">Choose district</option>
<option value="1">Area 1</option>
</select>
<span class="error">Find me</span>
</dd>
</dl>

Javascript:

// Form error messages
var result = {messages: {
'customer' : {
'customerName' : { 'isEmpty' : "Value is required and can't be empty"} ,
'address' : {
'address3' : { 'isEmpty' : "Value is required and can't be empty"}
},
'district' : {
'districtId' : { 'isEmpty' : "Value is required and can't be empty"}
},
}
}};

function parseMessages(messages, parent, result, prefix) {
result = result || [];
parent = parent || '';
prefix = prefix || [];
$.each(messages, function (name, value) {
var inputName = '';
if (prefix.length > 0) {
inputName += parent;
$.each(prefix, function(k, v){
inputName += '['+ v +']';
});
} else {
inputName = name;
}

var $input = $(':input[name="'+ inputName +'"]').eq(0);
if ($input.size()) {
console.log(inputName + ': Found');
} else {
console.log(inputName + ': Not found');
}
if ($input.size() > 0) {
// Move up a level
if (prefix.length > 0) {
prefix.pop();
}
// Error message:
// { isEmpty : "Value is required and can't be empty"}
// Messages to string
var messages = [];
if (typeof value == 'object') {
$.each(value, function(k, v) {
messages.push(v);
});
}
var errorMessage = messages.join(',');

// Add to result
$input.siblings('span').append(' -> <strong style="color:red">Found</strong>');
result.push({
element : $input,
message : errorMessage
});
} else {
if (!parent) {
parent = name;
} else {
prefix.push(name)
}
return parseMessages(value, parent, result, prefix);
}
});
return result;
}
console.log(result.messages);
var result = parseMessages(result.messages);
console.log(result)

参见 jsfiddle: http://jsfiddle.net/EeYs8/5/

enter image description here

我的脚本有问题,找不到 customer[district][districtId] 元素,热点解决了吗?非常感谢。

===================更新=========================== ======= enter image description here

最佳答案

将此添加到您的元素

if (name == "district"){
prefix.length = 0;
prefix.push(name);
}

See Demo

关于javascript - 从 json 中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com