如何将脚本src文件的输出字符串重定向到javascript中的变量

时间:2015-03-28 03:41:26

标签: javascript src

我已经找了几个小时看似简单的问题,并尝试过我在这里和其他地方找到的一些东西,但是无法回答这个问题。我运行一个广播电台,服务器以短脚本输出当前歌曲的名称。脚本是

    <script type="text/javascript" src="http://cdn.voscast.com/stats/display.js?key=33d86e1438d74956b30a556c434a952e&stats=songtitle"></script>

并且工作正常。我想要的东西相当于Linux&gt;或&gt;&gt;运算符,所以我可以将放到我的屏幕的数据存储到变量中,所以我可以在其他地方使用它。很抱歉,如果这是如此基本,但我已经尝试了许多不同的东西,只需要一些特定的简单代码来解决这个问题。感谢

1 个答案:

答案 0 :(得分:0)

使用jQuery尝试这样的事情。它是您问题的完整解决方案。

<html>
<head>

  <!-- This includes the jQuery library you need to extract the song name -->
  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>

  <!-- This is the script you want the song name from -->  
  <script type='text/javascript' src="https://cdn.voscast.com/stats/display.js?key=33d86e1438d74956b30a556c434a952e&stats=songtitle"></script>

</head>
<body>

<script type='text/javascript'>
    $(window).load(function(){
        $('div').filter(function() {
            return /^.{13}/.test(this.id);
        }).each(function() {

            $(this).hide(); // Hide the song name here

            // Assign the name to a variable as you requested
            var songName = this.innerHTML;

            // Just for a demonstration
            alert( songName );

            // Do what you like with the song name here ...
        });
    });
</script>

</body>
</html>

加载JavaScript文件时,会打印一个div并用歌曲名称填充它。 div id看起来是一个随机生成的13个字符的字符串。您可以使用jQuery选择过滤器访问该div - /^.{13}/.test(this.id)部分。