2013-03-06 65 views
0

我在javascript中遇到了变量问题。我的情况是:使用JavaScript进行变量冲突

在PHP文件,我有:

<div class="fd_text" onmouseover="zobraz_text('pom','1','1')" onmouseout="zobraz_text('pom','1','0')">something in</div> 

在JS文件,我有:

var pom1 = "Some text1"; 
var pom2 = "Some text2"; 

function zobraz_text(firma, cislo, udalost){ 
    obsah_text = firma+cislo; //this is wrong and why I wrote lower in text under this code 

    document.getElementById("bloks").innerHTML = document.getElementById("bloks").innerHTML + obsah_text; //this ID is correct 
} 

obsah_text是可变的,必须从pom1pom2等添加文本...
其中pom1pom2我从mouseover得到这是在PHP文件中。

如果我组首先从功能zobraz_text 2个parametrs我给pom1,但这pom1 isn't一样pom1在那里我有文字。在网上我有文字"pom1",但我必须有文字"Some text1"

当我删除变量obsah_text并简单地添加变量pom1(如本示例代码)时,我的代码有效。

这让我的文字从变量,这是确定的,但如果我添加变量那么这段代码只能在300情况1

document.getElementById("bloks").innerHTML = document.getElementById("bloks").innerHTML + pom1; 

我(对我有第一和功能zobraz_text()秒parametrs)相信你理解并帮助我。我希望这对你们很简单。

回答

3

您不能创建变量的变量。如果pom1pom2是全球性的,你可能会做window[firma + cislo],但我不会推荐这样做。

相反,使用对象来存储劲歌:

var poms = { 
    "pom1": "Some text1", 
    "pom2": "Some text2", 
} 
//snip 
obsah_text = poms[firma + cislo]; 
+0

它的工作原理,谢谢。 +1 – 2013-03-06 13:34:31