如何确保脚本运行一次且仅运行一次

发布于 2024-12-18 16:02:45 字数 336 浏览 3 评论 0原文

我正在编写一个小部件模板,它将包含在安装它的页面中。

人们可能会在一个页面中安装多个相同类型的小部件,因此我的模板可能会被包含多次。

现在我已经编写了一些 JavaScript 来初始化小部件,您知道,点击和悬停。

我的问题是这些

解决这个问题的最佳方法是什么?

编辑:
顺便说一句,我正在使用 Mako 模板引擎,并且我尝试使用 c 变量来存储布尔标志,但似乎 c每次都被覆盖。

I am writing a widget template, which will be included in a page where it is installed.

One may install several of the same kind of widget in one page, so my template may get included several times.

Now I have written some JavaScript to initialize the widget, you know, the clickings and hoverings.

My problem is that these <script>s get executed multiple times, for example, when I click something, the bounded function get executed several times.

What is the best way to solve this problem?

EDIT:
By the way, I am using the Mako template engine, and I've tried using the c variable to store a boolean flag, but it seems that the c get overridden every time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ懵逼小萝莉 2024-12-25 16:02:45

是否有一种与 C 中使用的类似解决方案来防止头文件被多次包含?

例如,在文件“example.html”中,您可以将代码包装在 if 语句中,如下所示:

<script type=text/javascript>
    if (!window._EXAMPLE_HTML_) {
        window._EXAMPLE_HTML_ = true;
        // your code goes here
    }
</script>

What about a similar solution to the one that's been used in C to prevent header-files to be included multiple times?

For example in the file "example.html" you could wrap your code in an if-statement like this:

<script type=text/javascript>
    if (!window._EXAMPLE_HTML_) {
        window._EXAMPLE_HTML_ = true;
        // your code goes here
    }
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文