【问题标题】:How to avoid js function overwritten when loading page from ajax.从ajax加载页面时如何避免js函数被覆盖。
【发布时间】:2012-12-20 14:13:27
【问题描述】:

例如:

--- 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页面调用自己的js函数的实用方法是什么?

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

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

谢谢。

【问题讨论】:

  • 欢迎来到 SO。请您详细解释您的问题以及您期望的答案。
  • 您可以使用 getter/setter 功能来防止覆盖函数/对象!

标签: javascript ajax jquery


【解决方案1】:

答案很简单。

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

除了在每个模块中正确解决问题之外,您真的没有其他现实的解决方案:

  1. 在每个模块中正确命名您的公共函数
  2. 使用Self Executing Function 模式在每个模块中限定您的私有函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2018-01-06
    • 2019-10-30
    • 2020-03-15
    相关资源
    最近更新 更多