JavaScript文件链接无法正常工作

4

我有四个不同的文件链接在一起。 Index.html - style.css - script.js - script2.js

script2.js包含了一个小型测试脚本来测试和查看它是否工作正常,它是可以工作的。

index.html 包含以下内容:

    <DOCTYPE html>
<html>
    <body>
        <head>
            <script type="text/javascript" src="jquery-1.12.1.min.js"></script>
            <script type="text/javascript" src="script.js"></script>
            <script type="text/javascript" src="script2.js"></script>
            <link rel="stylesheet" type="text/css" href="style.css">
        </head>
        <div id="container">
          <div id="message">
            <a id="animate" href="#">Transmit</a>
          </div>
        </div>
    </body>
<html>

现在我的script.js文件包含以下内容:
(function () {
    var $animate, $container, $message, $paragraph, MESSAGES, animate, initialise, scramble;
    MESSAGES = [];
    MESSAGES.push({
        delay: 0,
        text: 'Incoming transmission...'
    });
    MESSAGES.push({
        delay: 1200,
        text: 'You don\'t talk to anybody.'
    });
    MESSAGES.push({
        delay: 2200,
        text: 'You don\'t interact with anybody.'
    });
    MESSAGES.push({
        delay: 3600,
        text: 'Your whole sense of reality is, pretty warped...'
    });
    MESSAGES.push({
        delay: 5200,
        text: 'Does it bother you that we\'re not real?'
    });
    $container = $('#container');
    $message = $('#message');
    $animate = $('#animate');
    $paragraph = null;
    scramble = function (element, text, options) {
        var $element, addGlitch, character, defaults, ghostCharacter, ghostCharacters, ghostLength, ghostText, ghosts, glitchCharacter, glitchCharacters, glitchIndex, glitchLength, glitchProbability, glitchText, glitches, i, j, k, letter, object, order, output, parameters, ref, results, settings, shuffle, target, textCharacters, textLength, wrap;
        defaults = {
            probability: 0.2,
            glitches: '-|/\\',
            blank: '',
            duration: text.length * 40,
            ease: 'easeInOutQuad',
            delay: 0
        };
        $element = $(element);
        settings = $.extend(defaults, options);
        shuffle = function () {
            if (Math.random() < 0.5) {
                return 1;
            } else {
                return -1;
            }
        };
        wrap = function (text, classes) {
            return '<span class="' + classes + '">' + text + '</span>';
        };
        glitchText = settings.glitches;
        glitchCharacters = glitchText.split('');
        glitchLength = glitchCharacters.length;
        glitchProbability = settings.probability;
        glitches = function () {
            var j, len, results;
            results = [];
            for (j = 0, len = glitchCharacters.length; j < len; j++) {
                if (window.CP.shouldStopExecution(1)) {
                    break;
                }
                letter = glitchCharacters[j];
                results.push(wrap(letter, 'glitch'));
            }
            window.CP.exitedLoop(1);
            return results;
        }();
        ghostText = $element.text();
        ghostCharacters = ghostText.split('');
        ghostLength = ghostCharacters.length;
        ghosts = function () {
            var j, len, results;
            results = [];
            for (j = 0, len = ghostCharacters.length; j < len; j++) {
                if (window.CP.shouldStopExecution(2)) {
                    break;
                }
                letter = ghostCharacters[j];
                results.push(wrap(letter, 'ghost'));
            }
            window.CP.exitedLoop(2);
            return results;
        }();
        textCharacters = text.split('');
        textLength = textCharacters.length;
        order = function () {
            results = [];
            for (var j = 0; 0 <= textLength ? j < textLength : j > textLength; 0 <= textLength ? j++ : j--) {
                if (window.CP.shouldStopExecution(3)) {
                    break;
                }
                results.push(j);
            }
            window.CP.exitedLoop(3);
            return results;
        }.apply(this).sort(this.shuffle);
        output = [];
        for (i = k = 0, ref = textLength; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
            if (window.CP.shouldStopExecution(4)) {
                break;
            }
            glitchIndex = Math.floor(Math.random() * (glitchLength - 1));
            glitchCharacter = glitches[glitchIndex];
            ghostCharacter = ghosts[i] || settings.blank;
            addGlitch = Math.random() < glitchProbability;
            character = addGlitch ? glitchCharacter : ghostCharacter;
            output.push(character);
        }
        window.CP.exitedLoop(4);
        object = { value: 0 };
        target = { value: 1 };
        parameters = {
            duration: settings.duration,
            ease: settings.ease,
            step: function () {
                var index, l, progress, ref1;
                progress = Math.floor(object.value * (textLength - 1));
                for (i = l = 0, ref1 = progress; 0 <= ref1 ? l <= ref1 : l >= ref1; i = 0 <= ref1 ? ++l : --l) {
                    if (window.CP.shouldStopExecution(5)) {
                        break;
                    }
                    index = order[i];
                    output[index] = textCharacters[index];
                }
                window.CP.exitedLoop(5);
                return $element.html(output.join(''));
            },
            complete: function () {
                return $element.html(text);
            }
        };
        return $(object).delay(settings.delay).animate(target, parameters);
    };
    animate = function () {
        var data, element, index, j, len, options;
        for (index = j = 0, len = MESSAGES.length; j < len; index = ++j) {
            if (window.CP.shouldStopExecution(6)) {
                break;
            }
            data = MESSAGES[index];
            element = $paragraph.get(index);
            element.innerText = '';
            options = { delay: data.delay };
            scramble(element, data.text, options);
        }
        window.CP.exitedLoop(6);
    };
    initialise = function () {
        var index, j, len, text;
        $animate.click(animate);
        for (index = j = 0, len = MESSAGES.length; j < len; index = ++j) {
            if (window.CP.shouldStopExecution(7)) {
                break;
            }
            text = MESSAGES[index];
            $message.append('<p>');
        }
        window.CP.exitedLoop(7);
        $paragraph = $container.find('p');
        animate();
    };
    initialise();
}.call(this));

哪一个不起作用。为什么?我不明白为什么一个文件可以工作,而另一个不能...


尝试检查元素并查看是否正在加载script.js。也许您的文件路径不正确?尝试使用console.log()查看脚本运行到哪个点。 - Max
你创建了文件夹作为JS的JavaScript和CSS的样式吗? - Iqbal Pasha
window.CP是什么?我看你在调用它,但我没有看到它在任何地方被声明。如果它在你的第二个脚本文件中声明了,那么除非你延迟执行第一个脚本,否则它不会起作用。你的控制台中有哪些错误(如果有的话)? - Andrew
文件路径正确。至于windows.CP的问题,我不确定。老实说,这是来自codepen的代码(所有权归属于http://codepen.io/wagerfield/pen/wftcE),我正在尝试看看能否做些什么。但我总是遇到这样的问题,什么都不起作用。 - Warriorsfury
请不要编辑您的问题以添加类似“我仍在寻求帮助”的评论。这被认为是滥用编辑会将问题推到前面的事实。 - Heretic Monkey
如果你必须编辑,请编辑以包含你所指的“不起作用”的意思。你是指控制台中出现了错误吗?你是否尝试使用浏览器的调试器进行调试?基本上,阅读[询问]并确保你已经涵盖了所有要点。 - Heretic Monkey
4个回答

8
您的script.js不能正常工作,因为window.CP未定义。window.CP是CodePen的一部分,可防止无限循环挂起您的选项卡或浏览器。

http://codepen.io/wagerfield/pen/wftcE获取原始coffee script(而非已编译的内容),并使用http://js2.coffee将其转换为javascript,然后将其用作script.js。

以下是转换后的javascript代码(请将其用作您的script.js):

var $animate, $container, $message, $paragraph, MESSAGES, animate, initialise, scramble;

MESSAGES = [];

MESSAGES.push({
  delay: 0,
  text: "Incoming transmission..."
});

MESSAGES.push({
  delay: 1200,
  text: "You don't talk to anybody."
});

MESSAGES.push({
  delay: 2200,
  text: "You don't interact with anybody."
});

MESSAGES.push({
  delay: 3600,
  text: "Your whole sense of reality is, pretty warped..."
});

MESSAGES.push({
  delay: 5200,
  text: "Does it bother you that we're not real?"
});

$container = $("#container");

$message = $("#message");

$animate = $("#animate");

$paragraph = null;

scramble = function(element, text, options) {
  var $element, addGlitch, character, defaults, ghostCharacter, ghostCharacters, ghostLength, ghostText, ghosts, glitchCharacter, glitchCharacters, glitchIndex, glitchLength, glitchProbability, glitchText, glitches, i, j, k, letter, object, order, output, parameters, ref, results, settings, shuffle, target, textCharacters, textLength, wrap;
  defaults = {
    probability: 0.2,
    glitches: '-|/\\',
    blank: '',
    duration: text.length * 40,
    ease: 'easeInOutQuad',
    delay: 0.0
  };
  $element = $(element);
  settings = $.extend(defaults, options);
  shuffle = function() {
    if (Math.random() < 0.5) {
      return 1;
    } else {
      return -1;
    }
  };
  wrap = function(text, classes) {
    return "<span class=\"" + classes + "\">" + text + "</span>";
  };
  glitchText = settings.glitches;
  glitchCharacters = glitchText.split('');
  glitchLength = glitchCharacters.length;
  glitchProbability = settings.probability;
  glitches = (function() {
    var j, len, results;
    results = [];
    for (j = 0, len = glitchCharacters.length; j < len; j++) {
      letter = glitchCharacters[j];
      results.push(wrap(letter, 'glitch'));
    }
    return results;
  })();
  ghostText = $element.text();
  ghostCharacters = ghostText.split('');
  ghostLength = ghostCharacters.length;
  ghosts = (function() {
    var j, len, results;
    results = [];
    for (j = 0, len = ghostCharacters.length; j < len; j++) {
      letter = ghostCharacters[j];
      results.push(wrap(letter, 'ghost'));
    }
    return results;
  })();
  textCharacters = text.split('');
  textLength = textCharacters.length;
  order = (function() {
    results = [];
    for (var j = 0; 0 <= textLength ? j < textLength : j > textLength; 0 <= textLength ? j++ : j--){ results.push(j); }
    return results;
  }).apply(this).sort(this.shuffle);
  output = [];
  for (i = k = 0, ref = textLength; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
    glitchIndex = Math.floor(Math.random() * (glitchLength - 1));
    glitchCharacter = glitches[glitchIndex];
    ghostCharacter = ghosts[i] || settings.blank;
    addGlitch = Math.random() < glitchProbability;
    character = addGlitch ? glitchCharacter : ghostCharacter;
    output.push(character);
  }
  object = {
    value: 0
  };
  target = {
    value: 1
  };
  parameters = {
    duration: settings.duration,
    ease: settings.ease,
    step: function() {
      var index, l, progress, ref1;
      progress = Math.floor(object.value * (textLength - 1));
      for (i = l = 0, ref1 = progress; 0 <= ref1 ? l <= ref1 : l >= ref1; i = 0 <= ref1 ? ++l : --l) {
        index = order[i];
        output[index] = textCharacters[index];
      }
      return $element.html(output.join(''));
    },
    complete: function() {
      return $element.html(text);
    }
  };
  return $(object).delay(settings.delay).animate(target, parameters);
};

animate = function() {
  var data, element, index, j, len, options;
  for (index = j = 0, len = MESSAGES.length; j < len; index = ++j) {
    data = MESSAGES[index];
    element = $paragraph.get(index);
    element.innerText = '';
    options = {
      delay: data.delay
    };
    scramble(element, data.text, options);
  }
};

initialise = function() {
  var index, j, len, text;
  $animate.click(animate);
  for (index = j = 0, len = MESSAGES.length; j < len; index = ++j) {
    text = MESSAGES[index];
    $message.append("<p>");
  }
  $paragraph = $container.find("p");
  animate();
};

initialise();

// ---
// generated by coffee-script 1.9.2

4

我有一个朋友也遇到了同样的问题,但他想使用window.CP.shouldStopExecution。于是我检查了codepen的javascript文件,并找到了它来自哪个文件。

您可以将下面的内容保存为js文件,然后将其导入到您的javascript脚本中。之后,window.CP函数子集应该完全正常工作。

"use strict";"object"!=typeof window.CP&&(window.CP={}),window.CP.PenTimer={programNoLongerBeingMonitored:!1,timeOfFirstCallToShouldStopLoop:0,_loopExits:{},_loopTimers:{},START_MONITORING_AFTER:2e3,STOP_ALL_MONITORING_TIMEOUT:5e3,MAX_TIME_IN_LOOP_WO_EXIT:2200,exitedLoop:function(o){this._loopExits[o]=!0},shouldStopLoop:function(o){if(this.programKilledSoStopMonitoring)return!0;if(this.programNoLongerBeingMonitored)return!1;if(this._loopExits[o])return!1;var t=this._getTime();if(0===this.timeOfFirstCallToShouldStopLoop)return this.timeOfFirstCallToShouldStopLoop=t,!1;var i=t-this.timeOfFirstCallToShouldStopLoop;if(i<this.START_MONITORING_AFTER)return!1;if(i>this.STOP_ALL_MONITORING_TIMEOUT)return this.programNoLongerBeingMonitored=!0,!1;try{this._checkOnInfiniteLoop(o,t)}catch(o){return this._sendErrorMessageToEditor(),this.programKilledSoStopMonitoring=!0,!0}return!1},_sendErrorMessageToEditor:function(){try{if(this._shouldPostMessage()){var o={action:"infinite-loop",line:this._findAroundLineNumber()};parent.postMessage(JSON.stringify(o),"*")}else this._throwAnErrorToStopPen()}catch(o){this._throwAnErrorToStopPen()}},_shouldPostMessage:function(){return document.location.href.match(/boomerang/)},_throwAnErrorToStopPen:function(){throw"We found an infinite loop in your Pen. We've stopped the Pen from running. Please correct it or contact support@codepen.io."},_findAroundLineNumber:function(){var o=new Error,t=0;if(o.stack){var i=o.stack.match(/boomerang\S+:(\d+):\d+/);i&&(t=i[1])}return t},_checkOnInfiniteLoop:function(o,t){if(!this._loopTimers[o])return this._loopTimers[o]=t,!1;var i=t-this._loopTimers[o];if(i>this.MAX_TIME_IN_LOOP_WO_EXIT)throw"Infinite Loop found on loop: "+o},_getTime:function(){return+new Date}},window.CP.shouldStopExecution=function(o){var t=window.CP.PenTimer.shouldStopLoop(o);return t===!0&&console.warn("[CodePen]: An infinite loop (or a loop taking too long) was detected, so we stopped its execution. Sorry!"),t},window.CP.exitedLoop=function(o){window.CP.PenTimer.exitedLoop(o)};


奇怪的是,在CodePen本身中我也遇到了同样的错误,但将此代码复制到新的pen并将其作为外部.js资源引用解决了问题。奇怪...但没关系。 - ashleedawg

0

确保文件路径正确。

根据你的代码,你可以像这样包含你的JavaScript文件:

<script type="text/javascript" src="script.js"></script>

所以要确保你的文件index.html和script.js在同一个文件夹中。

如果不是的话,试着这样包含你的JavaScript文件:

<script type="text/javascript" src="../script.js"></script>

希望这会有所帮助。


请用文件夹结构进行解释。 - Ataur Rahman Munna
更改了文件夹设置,进行了测试,一切正常。除了测试(script2.js)文件和CSS外。我想要工作的script.js文件仍然无法正常工作。 - Warriorsfury
@Warriorsfury,能否告诉我你的javascript文件和css文件是否与.html文件在不同的文件夹中?请上传你的script2.js文件,这样我们就可以检查你的脚本了。因为也许你在不同的脚本(script.js和script2.js)中使用了function(){},这就是为什么另一个脚本无法工作的原因。 - kwingkwingko
脚本文件script2.js如下:alert("你好")很遗憾,我还没有解决这个问题... - Warriorsfury
尝试使用此代码 <script type="text/javascript" src="../java/script.js"></script> 如果仍然无法正常工作,请尝试将文件夹名称从“java”更改为“js”。 - kwingkwingko

0
首先,在浏览器中使用检查元素(F12)-> 网络或控制台,查看 script.js 的路径。使用 ~ 设置路径。 ~ 将设置为您的文件夹结构的根目录。
<script type="text/javascript" src="~/Set folder name from Root/script.js"></script>

如果您的文件位于Assets -> Script文件夹中,则路径将为“~/Assets/Script/script.js”。
<script type="text/javascript" src="~/Assets/Script/script.js"></script>

该文件的路径完全正确并且可用。 - Warriorsfury

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接