当前位置: 动力学知识库 > 问答 > 编程问答 >

How to redirect output string of script src file to a variable in javascript

问题描述:

I have looked for a couple of hours for what seemed like an easy question and have tried several things I've found here and elsewhere, but cannot answer this. I run a radio station and the servers outputs the name of the current song in a short script. The script is

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

and works fine. What I want is something that is the equivalent of the Linux > or >> operator so I can store the data that gets put to my screen into a variable instead, so I can use it elsewhere. Sorry if this is so basic, but I've tried a number of different things and just need some specific simple code to fix this. Thanks

网友答案:

Try something like this using jQuery. It is a complete solution to your question.

<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>

When the JavaScript file loads, it prints a div and populates it with the name of a song. The div id looks to be a randomly generated 13-character string. You can access that div using a jQuery selection filter - the /^.{13}/.test(this.id) part.

分享给朋友:
您可能感兴趣的文章:
随机阅读: