我在php中的关联数组中有一些城市列表。我使用javascript“on change”来获取每个项目的价值。我想将项目设置为默认项目(我想我将来考虑使用地理位置)。
这是我的数组:
// Array lists
$city_array = array(
array('id' => '1', 'name' => 'Aaaa'),
array('id' => '2', 'name' => 'Bbbb'),
array('id' => '3', 'name' => 'Cccc'),
array('id' => '4', 'name' => 'Dddd'),
array('id' => '5', 'name' => 'Eeee'),
);
$json_city = json_encode($city_array);
我的php功能:
// Decode
$cities = json_decode($json_city);
function display_cities() {
global $cities;
$output = '<select id="citylists" onChange="onSelectCity()">';
foreach( $cities as $city ) {
$output .= '<option class="itemcity" value="'.$city->id.'">'.$city->name.'</option>';
}
$output .= '</select>';
$output .= '<script type="text/javascript">
function onSelectCity() {
var cityLists = document.getElementById("citylists");
console.log(cityLists.value);
}
window.onload = function() {
onSelectCity();
}
</script>';
echo $output;
}
我希望输出像这样(用HTML打印):
<select id="citylists">
<option class="itemcity" value="1">Aaaa</option>
<option class="itemcity" value="2">Bbbb</option>
<option class="itemcity" value="3" selected>Cccc</option>
<option class="itemcity" value="4">Dddd</option>
<option class="itemcity" value="5">Eeee</option>
</select>
如您所见,我将默认值设为<option class="itemcity" value="3" selected>Cccc</option>
。
我怎样才能在动态php循环中做到这一点?
由于
答案 0 :(得分:0)
试试这个:
foreach( $cities as $city ) {
$selected = ($city->id == 3)?' selected ':null;
$output .= '<option class="itemcity" value="'.$city->id.'"'.$selected.'>'.$city->name.'</option>';
}
顺便说一下,对于有效的HTML,您应该将其更改为选中=&#34;已选择&#34;