我正在尝试通过javascript将用户重定向到另一个链接。当用户从单选框中选择一个选项并单击该按钮时,javascript会将用户重定向到类似的链接, sitename.com/events/text-which-user-selected-from-radio-box。我从php获取radiobox数据。这是我的代码,
<?php
foreach ($words as $word){
if($results > 3)
echo "<input name='tuh' type='radio' id='".str_replace(' ', '-', $word->name)."' value='".$word->name."'/>". $word->name."|".get_permalink($word->ID)."\n"."<br/>";
else
echo "<input name='tuh' type='radio' id='".str_replace(' ', '-', $word->name)."' value='".$word->name."'/>".$word->name."\n"."<br/>";
}
?>
<input type='button' value='write review' onclick="js_tuh()" />
此代码返回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并点击提交按钮时它会返回
TypeError:id_tuh为null [打破此错误]
if(id_tuh.checked == true){
请给我一个建议,我现在应该怎么做。
答案 0 :(得分:1)
id_tuh=document.getElementById("Amsterdam-Salsa-&-Zouk-Festival");
是错误的ID。这个HTML:
<input name='tuh' type='radio' id='Amsterdam-Salsa-&-Zouk-Festival' value='Amsterdam Salsa & Zouk Festival'/>
生成ID Amsterdam-Salsa-&-Zouk-Festival
- HTML实体在属性中仍被解释得很好 - 所以你需要使用它。
当然,更好的解决方案是生成并使用不包含&符号或大写字符的实际slug。
function slug($name) {
return preg_replace('/[^a-z]+/', '-', strtolower($name));
}
echo '<input name="tuh" type="radio" id="', slug($word->name),
'" value="', htmlspecialchars($word->name), '" />',
htmlspecialchars($word->name, ENT_NOQUOTES), '|',
get_permalink($word->ID), "\n<br/>";
此外,我必须在htmlspecialchars
中交换引号以确保准确性,但无论如何它看起来更好。