使用JavaScript的变量冲突


Variable conflict using 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是变量,必须添加pom1, pom2等文本…
其中pom1pom2我从mouseover这是在PHP文件。

如果我将函数zobraz_text的前两个参数分组,我给出了pom1,但这个pom1与我有文本的pom1不同。在网络上,我有文字"pom1",但我必须有文字"Some text1"

当我删除变量obsah_text并简单地添加变量pom1时,我的代码工作,如本示例代码所示。

这显示了变量的文本,这是可以的,但是如果我添加变量,那么这段代码只能在300种情况下的1种情况下工作(为此,我在函数zobraz_text()中有第一个和第二个参数)

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

我相信你理解我,帮助我。

不能创建变量的变量。如果pom1pom2是全局的,您可能会执行window[firma + cislo],但我不建议这样做。

使用一个对象来存储这些数据:

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