我需要生成具有json中描述的条件的按钮。请帮助我,我是新手,我被困住了。问题是我的代码生成了文本“未定义”的按钮,按钮点击没有任何反应。
这是我的JSON代码(由于http://www.jsoneditoronline.org/的检查结果有效,但不适用于下面的html代码):
{
"Caption": "Module caption",
"IconsDirectory": "C://Images/",
"Buttons": [
{
"Conditions": [
{
"ConditionText": "1 == 1",
"ButtonText": "Text1",
"Visible": true,
"Colors": {
"FontColor": "#FFFFFF",
"BGColor": "#669933"
},
"BButtonText": {
"TText": "Textt1"
},
"Size": {
"Width": 200,
"Height": 50
},
"Icon": {
"FileName": "Smile.png",
"Width": 16,
"Height": 16
},
"Url": {
"UrlAddress": "http://www.google.com",
"OpenNewWindow": true
},
"JavaScriptAction": {
"Text": "alert('ok');"
}
},
{
"ConditionText": "2 == 2",
"ButtonText": "Text2",
"Visible": true,
"Colors": {
"FontColor": "#0FFFFF",
"BGColor": "#FF9966"
},
"BButtonText": {
"TText": "Textt1"
},
"Size": {
"Width": 200,
"Height": 50
},
"Icon": {
"FileName": "Smile.png",
"Width": 16,
"Height": 16
},
"Url": {
"UrlAddress": "http://www.google.com",
"OpenNewWindow": true
},
"JavaScriptAction": {
"Text": "alert('ok');"
}
}
]
}
]
}
html代码:
<html>
<head>
<title>SMButtons</title>
<script src="jquery/jquery-1.4.2.js"></script>
<script type="text/javascript">
//When document loaded.
$(document).ready(function(){
// Get data from file as JSON
$.getJSON('weekendtask.json', function(data) {
//var buttons = data.Buttons;
//$.each(buttons, function(key, val)
//{
//$('<li><input type="button" onClick="'+ val.Conditions[0].JavaScriptAction +'" value="'+ val.Conditions[0].ButtonText +'"/> </li>').appendTo('#ulObj');
//$('<li><input type="button" value="'+ val.Conditions[1].BButtonText.TText +'"/></li>').appendTo('#ulObj');
var res=""
$.each(data.Buttons, function(key, button){
$.each(button.Conditions,function(key,condition){
// console.log(condition)
res+="<li>"
res+='<input type="button"' +
//'" value="'+ '"Ttt"' +
'" value="'+ condition.ButtonText +
//'" value="'+ data.Buttons.Conditions.ButtonText +
'" onclick="' + condition.JavascriptAction +
'" style="background-color:'+condition.Colors.BGColor+' color:'+condition.Colors.FontColor+
'"/>'
res+="<\/li><\/br><\/br>test<\/br>"
})
})
$(res).appendTo('#ulObj')
//});
});
});
window.onload = function(){ alert("welcome"); }
</script>
</head>
<body bgcolor="silver">
<br>
<br>
<div>
<ul id='ulObj'>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:1)
onClick
处理程序应为condition.JavaScriptAction.Text
。休息一切都很好。
var res = ""
$.each(data.Buttons, function(key, button) {
$.each(button.Conditions, function(key, condition) {
res += "<li>"
res += '<input type="button"' + '" value="' + condition.ButtonText + '" onclick="' + condition.JavaScriptAction.Text + '" style="background-color:' + condition.Colors.BGColor + ' color:' + condition.Colors.FontColor + '"/>'
res += "<\/li><\/br><\/br>test<\/br>"
})
})
$(res).appendTo('#ulObj')