我有javascript脚本:
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.mainForm.onclick = function(){
var radVal = document.mainForm.pages.value;
result.innerHTML = 'You selected: '+radVal;
}
}//]]>
</script>
单选按钮:
<form id="mainForm" name="mainForm">
<input name="pages" type="radio" value="p1">
<input name="pages" type="radio" value="p2">
<input name="pages" type="radio" value="p3">
</form>
<span id="result"></span>
<a href="http://localhost/folder/blabla.php?p=book'>Book</a>
我想要单击单击单选按钮,单选按钮上的值已放置在链接URL上,这样可以是:
link:<a href='http://localhost/folder/blabla.php?p=book&o=p1'>Book</a>
添加值&amp; o = p1
任何人都可以帮助我吗?
之前谢谢你
答案 0 :(得分:0)
您的表单不需要名称,这是多余的。您在函数中附加侦听器 this 的方式将引用表单,以便您可以执行以下操作:
window.onload=function(){
document.mainForm.onclick = function(event){
var radVal = this.rads.value;
// do stuff with radVal
}
对于您的解决方案,请考虑以下内容添加侦听器onload,然后在窗体内单击时有条件地修改URL。您可以在每个按钮上使用单击事件,或查看事件并查看它是否来自其中一个按钮,但我认为只需点击一次就可以更新URL更简单:
window.onload = function() {
var form = document.forms['mainForm'];
if (form) {
form.addEventListener('click', function() {
var link = document.getElementById('a0');
// Note that if there is only one such button, this will return a
// reference to the single element so maybe querySelectorAll is better
var buttons = this.pages;
// var buttons = this.querySelectorAll('[name=pages]');
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
// Add to the href or replace if previously added
link.href = link.href.replace(/\&.*|$/, '&o=' + buttons[i].value);
// debug
console.log(link.href);
// Stop once checked button is found
return;
}
}
}, false);
}
}