2013-03-05 72 views
0

我无法使用AJAX(服务器问题!),所以我不得不依靠DOM + javascript在我的页面上显示或隐藏两个div。DOM(Javascript)show/hide divs not working

用户单击两个单选按钮中的一个,并根据哪个单击,显示相应的div。

由于某些原因,如果使用“EU”单选按钮但第一个div会加载,但无法使用“国际”单选按钮来工作。第二个按钮调用正确的脚本,传递变量甚至隐藏EU div,它不会显示国际版本。

我在我的智慧结束。任何人都可以帮忙吗?

使用Javascript:

function displayLocation(loc){ 
    alert(loc) 
    document.getElementById(loc).style.display = "block" 
    if (loc == "eu"){ 
    document.getElementById("international").style.display = "none" 
    }else{ 
     document.getElementById("eu").style.display = "none" 
    } 
} 

HTML单选按钮

<input type="radio" name="loc" style="float:left;" onclick=displayLocation("eu")> 
<input type="radio" name="loc" style="float:left;" onclick=displayLocation("international")> 

Div的隐藏/显示适当

<div id="eu" style="display:none;">European Union</div> 
<div id="international" style="display:none;">International</div> 

回答

0

看看我刚​​刚制作的fiddle

我通过将放置在调用它的HTML后面的脚本来解决问题。还有一些风格的东西需要调整(onclick=displayLocation应该用引号括起来),但除此之外它应该适合你。

+0

我”已经做了这些变化,并没有好的测试 – useyourillusiontoo 2013-03-05 14:24:39

0

您需要在点击数属性环绕displayLocation('xx')报价为:'displayLocation("eu")'

http://jsfiddle.net/rvtBp/

我也建议使用,而不是事件事件绑定属性:

<input type="radio" name="loc" style="float:left;" data-lang="eu"> 
<input type="radio" name="loc" style="float:left;" data-lang="international"> 

Array.prototype.forEach.call(document.querySelectorAll('[name="loc"]'), 
function (elem) { 
    elem.addEventListener('change', function (e) { 
     if (this.checked) { 
      displayLocation(this.dataset.lang); 
     } 
    }); 
}); 

http://jsfiddle.net/rvtBp/1/

+0

- 这是不正确的 – useyourillusiontoo 2013-03-05 14:11:31

+0

@ user2040862你能更具体吗? – 2013-03-05 14:14:06

0
<input type="radio" name="loc" style="float:left;" onclick="displayLocation(\'' + eu + '\')"> 

的onclick声明应该用引号括起来.. onclick="displayLocation(\'' + eu + '\')"

我认为它不会工作.. document.getElementById(loc).style.display = "block"

document.getElementById("+loc+").style.display = "block" 
0

你必须改变onclick事件看起来像这样

<input type="radio" name="loc" style="float:left;" onclick="displayLocation('eu')"> 

<input type="radio" name="loc" style="float:left;" onclick="displayLocation('international')">