首页 > 解决方案 > 如何在刀片花括号中使用 javascript 变量

问题描述

我有一个视频播放器网站,我有一个“下一个”按钮,它应该停止视频,将 src 更改为指向下一个视频并使用 javascript 播放它,但我无法使用 javascript 循环来更改 src。

这是我的刀片文件

@extends('layouts.app')
@section('content')
<section class="player">
  <center>
    <video id="myvideo" class="playing-video" src="{{url('songs/'.$songs[0]->filename)}}" controls autoplay onended="nextVideo()">
    </video>
    <br>
    <button id="next" style="background-color: transparent;border: none;color: white;" onclick="nextVideo()" type="button">
    <h2><i class="fas fa-chevron-right"></i>Next</h2></button>
  </center>
</section>

这是不工作的javascript

var i = 0;
var myVideo = document.getElementById("myvideo");

function nextVideo() {
  i++;
  myVideo.setAttribute("src", "http://localhost/Laravel/anime/public/songs/" + {{ $songs[i] -> filename }});
  myVideo.load();
  myVideo.play();
}

我知道我不能直接在刀片花括号内使用 javascript 变量,但我没有想法!

标签: javascriptarrayslaravellaravel-blade

解决方案


将 Laravel 集合存储为按钮上的数据点:

<button id="next" data-songs="{{json_encode($songs)}}" ... etc />

然后在 nextVideo() JS 方法中拉出 JS 对象并循环它(所有 JS):

function nextVideo() {
    var songs = JSON.parse( //get the data from the #next button )
    //loop using the JS songs object instead of the blade {{}}
}

推荐阅读