javascript - 动态加载外部 javascript 并将其绑定(bind)到特定的 DOM 元素或命名空间

标签 javascript jquery dom dynamic

我希望能够动态加载外部 JavaScript 文件,然后将脚本中的方法绑定(bind)到 DOM 中的特定元素。那可能吗?如何?有什么限制?

我想象解决方案看起来像这样,但我对任何可行的方法持开放态度:

<html><body>
  <div class="A">aaaaa</div>
  <div class="B">bbbbb</div>
  <div class="A">aaa</div>
</body></html>

<script type="text/javascript">
  //This is the internal script, part of the original page
  $.get("url/outside_script.js",
    function(script_obj){
      $(".A").bind('niftyMethod', script_obj.niftyMethod)
    }
  );
</script>

这是外部脚本:outside_script.js

<script type="text/javascript">
  var script_obj = {
    niftyMethod : function(){
      //Do cool stuff in the context of a DOM object.
      $(this).fadeOut(500,function(){$(this).fadeIn(500)});
  }
</script>

我对此做了很多谷歌搜索,但没有发现太多。也许我使用了错误的搜索词...?

注意:如果需要的话,我很乐意使用 jquery。

最佳答案

一些更正:

脚本:

<script type="text/javascript">

    //add script to page
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "url/outside_script.js";
    $('body').append(script);

    //on document ready, bind your function
    $(function(){
        $(".A").bind('click', script_obj.niftyMethod)
    });

</script>

外部文件:

var script_obj = script_obj || {
    niftyMethod : function(){
      //Do cool stuff in the context of a DOM object.
      $(this).fadeOut(500,function(){$(this).fadeIn(500)});
  }

关于javascript - 动态加载外部 javascript 并将其绑定(bind)到特定的 DOM 元素或命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10344398/

相关文章:

javascript - 将数组存储在 html data 属性中

javascript - ajax 加载的内容与普通内容?

javascript - 为什么 Ractive.js 的 reset() 和 update() 方法在有一个带有 array.prototype.sort() 的助手和一个空对象的数据时复制模板

javascript - 在 Bluebird 中返回被拒绝的 promise 和 onPossiblyUnhandledRejection 处理程序

javascript - 如何在 Kendo UI numericTextBox 中保留尾随零?

jquery - IE7 : Absolutely positioned Child Div with a negative CSS value for 'right'

jquery - 点击后发布ajax变量

javascript - 从 JQuery-UI 包含中排除元素

jQuery (IBM Worklight) 页面导航和后退按钮

javascript - console.log 在 Chrome 浏览器中不显示输出