我对JS很新,也许这是一个非常平凡的问题,但我仍然无法弄清楚什么是错的。我有这个简单的HTML代码:用javascript更改onclick值
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
我想实现的是,基于收音机检查更改onclick属性。 例如,如果选中check1和check2,请转到google.com,如果check1和check3转到jsfiddle.net等等。所以我写了一个简单的JavaScript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here你可以找到一个JS提琴。 我想要做的就是像使用图像一样设置onclick属性,使用getElementById然后设置源代码,所以我写了document.getElementById('red')。onclick =“window.open('random page' )“但由于某些原因,我无法理解它不起作用。
问题:
1)你可以在我的代码看,我写了一个location.href =“地址”这显然doen't等待用户点击该按钮,所以这不是一个解决方案,我该如何做这项工作?
2)有没有办法让这段代码更具扩展性?我的意思是,在未来,如果我想添加另一个电台,我必须手动修改代码,并插入另一否则如果,我想到是这样的:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
任何建议,我的代码是值得欢迎。
如果我理解正确,onclick只接受函数作为值? –
这是如何将侦听器添加到JS中按钮上的点击浏览器事件。分配给onclick属性的函数将在onclick触发时执行。 –
谢谢你的回答。 –