2011-04-21 89 views
0

我已经在javascript中编写了两个单独的函数,并且我创建了一个全局变量。 第一个函数是设置全局变量的值,第二个函数是使用该全局变量来检查条件,但它不起作用。在JavaScript中维护变量的难度

这是我的代码。

var flag = 1; 

function setSelection(){ 

    for (index=0; index < top.parent.frmRadio.view.length; index++) { 
     if (top.parent.frmRadio.view[index].checked) { 
      var radioValue = top.parent.frmRadio.view[index].value; 

      if(radioValue == "graph"){ 
       flag = 1; 
       top.parent.test2.innerHTML = flag; 
      } 
      else{ 
       flag = 0; 
       top.parent.test2.innerHTML = flag; 

      } 

     } 
    } 
} 


function setFileName(name){ 
    var fileName = name; 
// document.getElementById("body").innerHTML = fileName; 
    document.getElementById("body").innerHTML = flag; 
    if(flag == 1){ 
     top.parent.frame2.location = fileName; 
     document.getElementById("body").innerHTML = fileName; 
    } 
    else{ 
     top.parent.frame2.location = "simpletree.html"; 
     document.getElementById("body").innerHTML = "simpletree.html"; 
    } 


// parent.frame2.location = fileName; 
} 

这两个函数都是由不同的地方调用的。单击单选按钮时调用第一个方法,单击列表时调用第二个方法。

+2

*“但它不会工作”*不会工作***如何***?你期望什么结果?你会得到什么结果?您是否在JavaScript控制台中看到任何错误?用调试器浏览时看到了什么? – 2011-04-21 05:04:23

回答

0

你的全局变量很好(全局变量很好,强烈建议避免它们)。

我认为问题出在setFileName函数中,那里有一些非常奇怪的操作。一些评论:

function setFileName(name){ 
    var fileName = name; 
// document.getElementById("body").innerHTML = fileName; 
    document.getElementById("body").innerHTML = flag; 
// ^-- Do you *really* have an element on the page with the id="body"? 
//  This will not change the `body` element of the page (unless you've given it that id). 
    if(flag == 1){ 
     top.parent.frame2.location = fileName; 
     document.getElementById("body").innerHTML = fileName; 
//  ^--- This will replace the content of the element with id="body" with 
//   the text of the filename (it will not retrieve the file) 
    } 
    else{ 
     top.parent.frame2.location = "simpletree.html"; 
     document.getElementById("body").innerHTML = "simpletree.html"; 
//  ^--- This will replace the contents of the element with id="body" 
//   with the text "simpletree.html", it will not retrieve the file 
    } 


// parent.frame2.location = fileName; 
} 

设置元素的innerHTML改变其内容所指派的实际文本。它不会加载页面并将页面的内容放在那里。为此,您必须使用iframe或使用ajax加载页面内容(来自同一来源的服务器),然后分配生成的文本/标记。

+0

我正在使用这个“innerHTML”来检查它是否得到正确的输入 – Ashish 2011-04-21 05:12:54

+0

@Ashish:还有其他几点?特别是,你真的有'id'“body”元素吗? – 2011-04-21 05:23:29

+0

@ T.J.拥挤是的,我有,但那只是为了测试目的,当它会正常工作,那么我会删除它。 – Ashish 2011-04-21 05:29:52