javascript - 保持脚本元素独立

标签 javascript jquery html django

简短版本:如何保留不同<script>的内容元素相互独立吗?

长版本:我有一个 django 模板,看起来有点像这样:

<div class="app-container">
  <script src="app.js"></script>
  <script>
    $(function() {
        app_init($('.app-container')); // app_init is defined in app.ja
    });
  </script>
</div>

困难在于我希望能够在同一页面中多次包含此模板。当我这样做时,$('.app-container')选择器匹配所有 <div class="app-container">页面上的元素。

保持这些独立性的最佳方法是什么?我能想到一些选项,但不太明白如何使它们发挥作用:

  • 查找<div ...>标签是 <script> 的父标签标签。如果脚本是自动执行的,那么我可以使用 document.scripts[-1] 来查看它是如何工作的。但当代码在 $(function () { ... }) 中执行时,我无法发现如何执行此操作.
  • 分配 <div> 的类以编程方式标记,然后在 javascript 中以编程方式找出相同的类。但我不知道该怎么做。
  • 巧妙地使用匿名函数并捕获了这一点,但我还是不太明白。

编辑我看到人们提出了对此的各种变体:

<div class="app-container">
  <script>
    var thisscript = document.currentScript;
    $(function() {
      app_init($(thisscript).closest('.app-container'));
    });
  </script>
</div>

如果在页面中多次使用模板,则此方法不起作用,如 thisscript变量在它们之间是通用的,因此它始终是最后一个 div.app-container在被处理的页面中。

最佳答案

这是一种可能有效的技术。您必须弄清楚全局变量问题。

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<script>
  var thisScript = [];
</script>

<body>

  <div class="app-container">
    some text
    <p>one</p>
    <script src="app.js"></script>
    <script>
      thisScript.push(document.currentScript);
      console.log(1);
      $(function() {
        //app_init($('.app-container')); // app_init is defined in app.js
      });
    </script>
  </div>

  <div class="app-container">
    second instance
    <p>two</p>
    <script src="appy.js"></script>
    <script>
      thisScript.push(document.currentScript);
      console.log(2);
      $(function() {
        //alert( script );
        //app_init(script); // app_init is defined in app.js
      });
    </script>
  </div>

  <div class="app-container">
    here is poor html
    <p>last</p>
    <script src="appy.js"></script>
    <script>
      thisScript.push(document.currentScript);
      console.log(3);
      $(function() {
        /**/
      });
    </script>
  </div>

  <script>
    console.log(thisScript);
  </script>
</body>

</html>

此外,请参阅这篇文章以了解可能适合您的情况的更多选项:How may I reference the script tag that loaded the currently-executing script?

关于javascript - 保持脚本元素独立,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430282/

相关文章:

javascript - 获取基于类的索引

javascript - 链接 Knockout 自定义绑定(bind)

jquery - Zend 表单 : How to create a 'create account form' that checks for unique username?

html - 结合 CSS3 转换保持引用系统

javascript - jQuery 验证 : abstracting rules

javascript - 用 div 包装链接组? (PHP 是一种选择)

jquery - 使用 ajax 或 post back to post 操作的差异

javascript - 当我单击与之对应的复选框时,如何使不可编辑的文本框变为可编辑

html - 三列响应式

html - 粘性 HTML 表格标题几乎可以使用,但标题上方的行略微可见