在同一页面上运行2个相同的javascripts

时间:2011-01-06 11:37:05

标签: javascript

这是一个普遍的问题。我有一个javascript我想在同一页面上使用两次。很明显,每当我与其中一个进行交互时 - 它将改变另一个。我知道在其中重命名方法名称将解决此问题,但我无法访问它。 有没有办法让他们都能在没有碰撞的情况下工作?

我想在其他名字的javascript中包装它们,但我被困在这里。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这是一个设计问题。

解决这个问题的最好方法是以面向对象的方式设计代码,使用JS类(我知道很多人会告诉我JS没有类,但它确实适用于所有意图和目的)。 / p>

例如:

// Define the class
function myobject() {

  // Variables belonging to this class
  this.value1 = 0;
  this.value2 = 0;
  this.total = 0;

  // A function within this class
  this.addNumbers = function(){
      this.total = this.value1 + this.value2;
  }
}

// Create two instances of the class
var mything = new myobject();
var mything2 = new myobject();

// Set variables within the instances
mything.value1 = 5;
mything2.value1 = 10;

// Run the function
mything.addNumbers();
mything2.addNumbers();

// Show the result
alert(mything.total);
alert(mything2.total);

您现在有两个myobject实例,它们不会相互冲突。这个类也可以在其中包含函数。

因此,在您的情况下,可能值得包装您在类中的JS,然后创建该类的实例。

答案 1 :(得分:0)

document.scripts[Name - or - index].method()

OR 加载不同的文档。即,在iframe文档中加载第二个脚本并使用它。

相关问题