好的,我正在努力创建一个可以在选择框中使用的对象数组......
这是我到目前为止的代码:
var oTranslators = {{"bosniancroatianserbian" : null} , {"dutch" : {"name":"willemjan","id":2}} , {"german" : {"name":"chilly","id":11}} , {"german_informal" : {"name":"Boantio","id":1640}} , {"greek" : null} , {"hungarian" : {"name":"Rudi","id":69}} , {"norwegian" : null} , {"russian" : {"name":"Bugo","id":43}} , {"spanish" : {"name":"Diego Andr\u00e9s","id":413}} };
function lang_switch(val)
{
if (val == 1)
document.getElementById("lang").innerHTML = '<select name="lang_name" onchange="trans_switch(this.selectedIndex);"><option value="bosniancroatianserbian">Bosnian/Croatian/Serbian</option><option value="dutch">Dutch</option><option value="german">German</option><option value="german_informal">German Informal</option><option value="greek">Greek</option><option value="hungarian">Hungarian</option><option value="norwegian">Norwegian</option><option value="russian">Russian</option><option value="spanish">Spanish</option></select><label for="translator">Translator: <select name="translator" id="translator"></select></label>';
else
document.getElementById("lang").innerHTML = '';
}
function trans_switch(oBName)
{
document.upload.translator.options.length = 0;
var oBoard = oTranslators[oBName];
for (var i = 0; i < oBoard.length; i++) {
translator.options[translator.options.length] = new Option(oBoard.name, oBoard.id, false, false);
}
}
HTML:
<form name="upload" enctype="multipart/form-data" action="http://mydomain.com/myaction.php" method="post" autocomplete="off">
<dl class="settings">
<dt>
<strong>Choose a file to upload:</strong>
</dt>
<dd>
<input type="file" name="dp_file" size="38" class="input_file" />
</dd>
<dt>
<select name="down_area" onchange="lang_switch(this.value);">
<option value="0">Main Download</option>
<option value="1">Language Packs</option>
</select>
</dt>
<dd>
<div id="lang"></div>
</dd>
</dl>
<div style="text-align: right;"><input name="upload" type="submit" value="Upload" class="button_submit" /></div>
</form>
基本上,我收到错误声明lang_switch
未定义,这很疯狂,因为它就在那里。我的对象数组有问题吗?我没有正确定义吗?这是来自json_encode
,但它是一个多维数组,我不得不修复它,所以使用这个PHP代码修复它,在for循环中:
$oTrans = '';
$i = 0;
foreach($context['languages'] as $lang => $language)
{
$i++;
$oTrans .= '{"' . $lang . '" : ' . json_encode($language['translator'][$lang]) . '} ' . (count($context['languages']) == $i ? '};' : ', ');
我不这样做吗?上面的oTranslators
对象数组有什么问题?
答案 0 :(得分:0)
您面临的问题是,当您尝试创建javascript对象数组时,您尝试使用对象括号初始化数组:{
。
结果会给您一个错误,因为您无法通过以下方式初始化对象:
{{Prop1:val}, {Prop2:val}};
需要如下:
{Prop1:val, Prop2:val};
因此,要修复数组,您需要做的就是将第一个{
和最后一个}
替换为数组括号[
和]
:
[{"bosniancroatianserbian" : null} , {"dutch" : {"name":"willemjan","id":2}} , {"german" : {"name":"chilly","id":11}} , {"german_informal" : {"name":"Boantio","id":1640}} , {"greek" : null} , {"hungarian" : {"name":"Rudi","id":69}} , {"norwegian" : null} , {"russian" : {"name":"Bugo","id":43}} , {"spanish" : {"name":"Diego Andr\u00e9s","id":413}} ];