我有以下对象:
{
builders: [
{
name: "Branches > Build",
slaves: [
"slave-01.local"
]
},
{
name: "Branches > Build1",
slaves: [
"slave-02.local"
]
}
]
}
如果他们的父tr id与json的name属性匹配,我想更新html表td。
<table>
<tr id="Branches > Build" class="odd">
<td>
value of slaves of Branches > Build should be here
</td>
<tr id="Branches > Build1" class="even">
value of slaves of Branches > Build1 should be here
<td>
</td>
<table>
我如何实现这一目标?我正在使用jquery。
顺便说一下。我无法获得没有空格的id,因此必须使用它。
答案 0 :(得分:1)
如果您无法将ID更改为有效ID,则可以使用属性选择器[id=""]
var obj = "the jsonfile";
var objBuilder = obj.builders;
for (var key in obj) {
var item = $('[id="' + obj[key].name + '"]')
if (item.length) {
item.find('td').text(obj[key].slaves);
}
}
DEMO修复了html标记以及
答案 1 :(得分:0)
你能试试吗,
var json = {
builders: [
{
name: "Branches > Build",
slaves: [
"slave-01.local"
]
},
{
name: "Branches > Build1",
slaves: [
"slave-02.local"
]
}
]
}
$("table tr").each(function(index, obj){
console.log(index+obj.id + json.builders[0].name);
if(obj.id == json.builders[0].name){
$(this).find('td').html('test');
}
});
答案 2 :(得分:0)
请参阅basic types
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number
of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
IDREF and IDREFS are references to ID tokens defined by other attributes. IDREF is a single token and IDREFS is a space-separated list of tokens.
NUMBER tokens must contain at least one digit ([0-9]).
所以你可能必须找到一种更好的方法来解决它并使用正确的ID。我建议你去使用"Aungular"这样的javascript框架,这样可以让你的工作变得更简单,你可以用它做更多的事情。