【问题标题】:Proper way to include one js file in another将一个js文件包含在另一个文件中的正确方法
【发布时间】:2016-09-30 08:19:47
【问题描述】:

from this answer 我都试过了,但都不起作用:

$(function () {
  var imported = document.createElement('script');
  imported.src = '/assets/admin/receipt_zooming.js';
  document.head.appendChild(imported);

  $('.rotate-receipt').on('click', rotateImage());
  $('.zoom-in').on('click', zoomHandler('+'));
  $('.zoom-out').on('click', zoomHandler('-'));

// 或

  $.getScript('/assets/admin/receipt_zooming.js', function()
  {
    $('.rotate-receipt').on('click', rotateImage());
    $('.zoom-in').on('click', zoomHandler('+'));
    $('.zoom-out').on('click', zoomHandler('-'));
  });
});

receipt_zooming 文件:

$(function () {
  return function() {
  var zoomHandler = function(sign) {
    return function() {
      var index = $(this).data('button-index');
      var image = $('#receipt-image-' + index);
      switch (sign) {
        case '+':
          image.width(image.width() + 100);
          break;
        case '-':
          image.width(image.width() - 100);
      }
    };
  };
  var rotateImage = function () {
    var angle = 0;
    return function() {
      var index = $(this).data('button-index');
      angle = (angle + 90)%360;
      var className = 'rotate' + angle;
      $('#receipt-image-'+index).removeClass().addClass(className);
    };
  };
}
});

我需要在其他几个文件中包含receipt_zooming.js。请帮忙。

编辑:我能知道为什么有人-1而不是帮助吗?

【问题讨论】:

  • I need to include the receipt_zooming.js in a few another files 是什么意思???您不会将一个 js 文件包含到另一个 js 文件中,而是将两个文件都包含在 HTML 页面中......或者您从 js 文件加载另一个以包含在页面上
  • 使用文本编辑器并在所需页面的头部添加一个脚本标签,其中 src 是您文件的路径
  • 我无法将它包含在 html 文件中,它是一个 rails 应用程序
  • 这两种方法都可以,但你需要包含 jQuery。你有错误吗?
  • 试试这个帖子:stackoverflow.com/questions/950087/…var imported = document.createElement('script'); imported.src = '/path/to/imported/script'; document.head.appendChild(imported);

标签: javascript jquery ruby-on-rails


【解决方案1】:
function loadScript(file) {
   var imported = document.createElement('script');
  imported.src = '/assets/admin/receipt_zooming.js';
  imported.type = "application/javascript";
  document.head.appendChild(imported);       
}

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 2011-07-31
  • 2012-05-01
  • 1970-01-01
  • 2011-07-17
相关资源
最近更新 更多