简体   繁体   English

为什么不能声明变量,将其转换为整数并在代码中使用该整数?

[英]why can't I declare a variable, convert it to an integer and use that integer in my code?

I am trying to create a playlist of audio files. 我正在尝试创建音频文件的播放列表。 The html contains three audio tags: html包含三个音频标签:

<ul id="myAudio">
    <li>
        <audio class="audio" id="1" controls>
            <source src="_audio/Clear_Vision.mp3" type="audio/mpeg" />
        </audio>
    </li>
    <li>
        <audio class="audio" id="2" controls>
            <source src="_audio/Greensleeves.mp3" type="audio/mpeg" />
        </audio>
    </li>
    <li>
        <audio class="audio" id="3" controls>
            <source src="_audio/Pavane21Sec.mp3" type="audio/mpeg" />
        </audio>
    </li>
</ul>

so far my javascript(jquery) is: 到目前为止,我的javascript(jquery)是:

$(document).ready(function(){
    var audioElement = document.createElement('audio');

    var x = 1;
    x = parseInt(x);


    var deisredAudio = $('source:nth(0)').attr('src');

    audioElement.setAttribute('src', deisredAudio);

    $.get();

    audioElement.addEventListener("load", function(){
        audioElement.play();
    }, true);

    $('#playAudio').click(function(){
        audioElement.play();
    });

    $('#pauseAudio').click(function(){
        audioElement.pause();
    });
});

This will play the audio track as long as I have an integer in the $('source:nth(0)') . 只要$('source:nth(0)')有一个整数,这就会播放音频轨道。

This will play the first audio, $('source:nth(1)') will play the second and so on as expected. 这将播放第一个音频, $('source:nth(1)')将播放第二$('source:nth(1)')音频,依此类推。

What I need to do is insert a variable to eventually create a loop to loop through and play the audio tracks. 我需要做的是插入一个变量,最终创建一个循环来循环播放音频轨道。

When I declare a variable x = 1 , and then insert it into $('source:nth(x)') , it does not work. 当我声明一个变量x = 1 ,然后将其插入$('source:nth(x)') ,它不起作用。

Please note that I am self-taught in JavaScript. 请注意,我是使用JavaScript自学的。

Any help or insight will be greatly appreciated. 任何帮助或见识将不胜感激。

You need to take it out of quotes and pass it into your :nth() using string concatenation: 您需要使用引号将其移出引号并将其传递到您的:nth()

$('source:nth(' + x + ')')

...otherwise you're using the character literal "x". ...否则,您将使用字符文字“ x”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM