从ajax加载页面时如何避免js函数被覆盖。

时间:2012-12-20 05:08:11

标签: javascript ajax jquery

例如:

--- a.php ---
<script>
function fun() {
   console.log('this is fun() from a.php');
}
function loadb() {
   $("#loadb").load("b.php");
}
function removeb() {
   $("#loadb").remove();
}
</script>
This is a.php
<input type="button" onclick="fun()" value="echo fun">
<input type="button" onclick="loadb()" value="load b.php">
<input type="button" onclick="removeb()" value="remove b.php">
<div id="loadb"></div>

--- b.php ---
<script>
function fun() {
   console.log('this is fun() from b.php');
}
</script>
This is b.php

从Ajax加载b.php后,a.php中的“fun()”将被覆盖 即使我删除了b.php,b.php中的fun()仍保留在页面中。

确保ajax-ed页面调用它自己的js函数的实用方法是什么?

Cos a.php将加载由不同开发人员开发的许多其他页面 他们可能会在页面中编写自己的js函数,有时它们的函数会有共同的命名,如:remove(),add()......等。

我想知道,是否有任何有效的方法可以避免这种情况?

感谢。

1 个答案:

答案 0 :(得分:1)

答案很简单。

由于脚本标记附加到DOM后浏览器会执行什么操作,因此无法保护函数不被脚本所做的某些分配所覆盖。

在每个模块中,你真的没有其他解决方案,而不是正确的解决方案:

  1. 在每个模块中正确命名您的公共职能
  2. 使用Self Executing Function模式
  3. 在每个模块中展开您的私有函数