我正嘗試通過javascript將用戶重定向到另一個鏈接。當用戶從收音機框中選擇一個選項並點擊該按鈕時,javascript會將用戶重定向到一個鏈接,如: sitename.com/events/text-which-user-selected-from-radio-box。我從php.Here獲取radiobox數據是我的代碼,如何在JavaScript中解決TypeError:getElementById null
此代碼返回HTML這樣,
<input name='tuh' type='radio' id='Amsterdam-International-Salsa- Congress' value='Amsterdam International Salsa Congress'/>Amsterdam International Salsa Congress|
<br/>
<input name='tuh' type='radio' id='Amsterdam-Salsa-&-Zouk-Festival' value='Amsterdam Salsa & Zouk Festival'/>Amsterdam Salsa & Zouk Festival|
我還使用內部JavaScript的PHP的,這是我的javascript代碼,
<script type='text/javascript'>
function js_tuh(){
<?php
foreach ($words as $word){
?>
id_tuh=document.getElementById("<?php echo str_replace(' ', '-', $word->name); ?>");
if(id_tuh.checked == true){
// alert(id_tuh.value);
window.location = "http://beta.salsatraveladvisor.com/events/"+id_tuh.id;
}
<?php } ?>
}
</script>
和php返回這樣的javascript代碼,
<script type='text/javascript'>
function js_tuh(){
id_tuh=document.getElementById("Amsterdam- International-Salsa-Congress");
if(id_tuh.checked == true){
alert(id_tuh.value);
//alert(id_tuh.value);
//window.location.replace("http://www.salsatraveladvisor.com/events/"+id_tuh.value);
window.location = "http://beta.salsatraveladvisor.com/events/"+id_tuh.id;
}
id_tuh=document.getElementById("Amsterdam-Salsa-&-Zouk-Festival");
if(id_tuh.checked == true){
alert(id_tuh.value);
//alert(id_tuh.value);
//window.location.replace("http://www.salsatraveladvisor.com/events/"+id_tuh.value);
window.location = "http://beta.salsatraveladvisor.com/events/"+id_tuh.id;
}
}
</script>
當我點擊第一個單選框並點擊按鈕,它工作正常。但是,當我選擇第二radiobox並點擊提交按鈕返回
類型錯誤:id_tuh是空 [打破這個錯誤]
如果(id_tuh.checked ==真){
請給我建議我現在應該做什麼。
請不要寫'== true'。 – Ryan
我不認爲你的ID是有效的。 – j08691