Когда я нажимаю кнопку поворота, я хочу, чтобы отображались имя, возраст и местонахождение? Как получить доступ к переменной nextContestant в функции? - PullRequest
0 голосов
/ 21 июня 2020

Проблема в том, что функция buttonSound не имеет ссылки на переменную currentContestant, которая находится в функции nextContestant, и у меня возникли проблемы с исправлением того, что любая помощь будет оценена по достоинству. Я пробовал объявить его глобально, но это не помогло, попробовал вызвать функцию b внутри функции a, и это не сработало. Я уверен, что это простое исправление, которое я не совсем понимаю.

// Temporary hardcoded data
const data = [
    {
        name: 'Dua Lipa',
        age: 22,
        location: 'UK',
        song: 'Arctic Monkeys - Do I Wanna Know?',
        link:'https://www.youtube.com/embed/fZB-ptAnoQc?start=26'
    },
    {
        name: 'James Arthur',
        age: 23,
        location: 'UK',
        song: 'Frankie Vallie - Cant Take my Eyes Off you',
        link:'https://www.youtube.com/embed/JUeEcdS-aa0?start=12'
       
    },
    
];


document.querySelector('.turn-button').addEventListener('click', buttonSound);

// Create event for next button
document.querySelector('.next').addEventListener('click', nextContestant);


// pass the data in the profileIterator function
const contestants = profileIterator(data);


// Call first profile
nextContestant();




// Next profile Display
function nextContestant() {
    const currentContestant = contestants.next().value;
   
 
    // Add a condition if it finishes looping through the array
    if(currentContestant !== undefined){
    document.querySelector('#profileDisplay').innerHTML = `
    <iframe class="hidden-vid" width="560" height="315" src="${currentContestant.link}&rel=0&autoplay=1&mute=2" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
    <div id="imageDisplay"><img class="anon"
                            src="media/anon.png"></div>
    <ul class="list-group">
        <li class="list-group-item" id="name">Name: ? 
        </li>
        <li class ="list-group-item" id="age">Age: ?
        </li>
        <li class ="list-group-item" id="location">Location: ?
        </li>
        <li class ="list-group-item">Song: ${currentContestant.song} 
        </li>
    </ul>
    `;
    } else {
        // No more contestants
        window.location.reload();
    }
    return {
        contestant: currentContestant
    }

    // document.querySelector('#imageDisplay').innerHTML = `<img
    // src="${currentContestant.image}">`;
}

// Profile Iterator
function profileIterator(contestants) {
    // counter
let nextIndex = 0;

// return object with next function
return {
    next: function(){
        return nextIndex < contestants.length ?
        {value: contestants[nextIndex++], done: false} :
        {done: true}
    }
};

}



function buttonSound(){

    const sound = document.querySelector('#audio');
    sound.play();
    document.querySelector(".anon").style.display = 'none'
    document.querySelector("iFrame").style.display='block';
    document.querySelector("#name").innerText=`Name: ${currentContestant.name}`;
    document.querySelector("#age").innerText=`Age: ${currentContestant.age}`;
    document.querySelector("#location").innerText=`Location: ${currentContestant.location}`;
    // document.querySelector('#imageDisplay').innerHTML = `<img
    // src="${currentContestant.image}">`;
}
* {
    margin: 0;
    padding: 0;
}

.turn-button {
    padding: 3rem;
    color: white;
    background-color: red;
    text-align: center;
    font-size: 2rem;
    border-radius: 50%;
    cursor: pointer;
    border: 0.3rem solid white;
    box-shadow: 0 1.5rem black;
    text-decoration: none;
    align-self: center;
}

/* :active an element being activated by a user */
.turn-button:active {
    transform: translateY(1rem);
    box-shadow: 0rem 1rem black;
    transform: translateY(4px);
}

.next {
    background-color: black;
    color: white;
    margin-left: 10rem;
    align-self: center;
    font-size: 1.5rem;
    cursor: pointer;
    padding: 1.5rem;
}

.stage {
    width: 100%;
    position: relative;
    /* width: 100%; */
    overflow: hidden;
    /* position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%); */
    z-index: -1;
}

video {
    width: 100%;
    /* position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%); */
    z-index: -1;
}

.profile {
    position: absolute;
    top: 20%;
    left: 6%;
}

.judges-panel {
    display: flex;
    background-color: grey;
    justify-content: center;
    align-items: center;
}

iframe {
    display: none;
}

img {
    height: 15rem;
    width: 15rem;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta
            name="viewport"
            content="width=
    , initial-scale=1.0"
        />
        <link rel="stylesheet" href="style.css" />
        <link
            rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous"
        />
        <title>Document</title>
    </head>
    <body>
        <div class="stage">
            <video id="videoBG" poster="media/poster.png" autoplay muted loop>
                <source src="media/vid-background.mp4" type="video/mp4" />
            </video>
            <div class="container profile">
                <div class="row">
                    <div class="col-md-6 mx-auto text-center">
                        <h1 class="mb-3"></h1>
                        <br />
                        <div id="profileDisplay"></div>
                        <br />
                    </div>
                </div>
            </div>
        </div>

        <div class="judges-panel">
            <button class="turn-button">TURN</button>
            <audio id="audio" src="media/button-sound.mp3"></audio>
            <button class="next">Next Contestant</button>
        </div>
        
        <!-- <iframe class="hidden-vid" width="560" height="315" src="https://www.youtube.com/embed/c8m6kBF5ML8?rel=0&autoplay=1&mute=2" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> -->
       
        
        </iframe>

        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script
            src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
            integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
            crossorigin="anonymous"
        ></script>
        <script
            src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
            integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
            crossorigin="anonymous"
        ></script>
        <script
            src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
            integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
            crossorigin="anonymous"
        ></script>
        <script src="app.js"></script>
    </body>
</html>

Ответы [ 2 ]

1 голос
/ 21 июня 2020

Все дело в области видимости; var - область видимости функции, let - область видимости блока, а const - для переменных, которые имеют фиксированное значение, которое нельзя изменить (постоянная переменная). У вас есть currentContestant, определенное как константа с областью видимости внутри функции nextContestant, что не имеет смысла, поскольку меняет значение каждый ход игрока. Если вы хотите сделать его глобальным, определите его как var nextContestant = null; вне какой-либо функции.

0 голосов
/ 21 июня 2020

Чтобы добавить к ответу Питера Брэнда, это действительно имеет какое-то отношение к сфере действия. Поскольку вы определяете переменную в функции, она недоступна в глобальной области видимости. Я добавил переменную в опубликованный вами скрипт и запустил его на CodePen, и кажется, что все работает :)

// Temporary hardcoded data
const data = [
    {
        name: 'Dua Lipa',
        age: 22,
        location: 'UK',
        song: 'Arctic Monkeys - Do I Wanna Know?',
        link:'https://www.youtube.com/embed/fZB-ptAnoQc?start=26'
    },
    {
        name: 'James Arthur',
        age: 23,
        location: 'UK',
        song: 'Frankie Vallie - Cant Take my Eyes Off you',
        link:'https://www.youtube.com/embed/JUeEcdS-aa0?start=12'
       
    },
    
];


document.querySelector('.turn-button').addEventListener('click', buttonSound);

// Create event for next button
document.querySelector('.next').addEventListener('click', nextContestant);


// pass the data in the profileIterator function
const contestants = profileIterator(data);

let currentContestant;

// Call first profile
nextContestant();

// Next profile Display
function nextContestant() {

    currentContestant = contestants.next().value;

    // Add a condition if it finishes looping through the array
    if(currentContestant !== undefined){
    document.querySelector('#profileDisplay').innerHTML = `
    <iframe class="hidden-vid" width="560" height="315" src="${currentContestant.link}&rel=0&autoplay=1&mute=2" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
    <div id="imageDisplay"><img class="anon"
                            src="media/anon.png"></div>
    <ul class="list-group">
        <li class="list-group-item" id="name">Name: ? 
        </li>
        <li class ="list-group-item" id="age">Age: ?
        </li>
        <li class ="list-group-item" id="location">Location: ?
        </li>
        <li class ="list-group-item">Song: ${currentContestant.song} 
        </li>
    </ul>
    `;
    } else {
        // No more contestants
        window.location.reload();
    }
    return {
        contestant: currentContestant
    }

    // document.querySelector('#imageDisplay').innerHTML = `<img
    // src="${currentContestant.image}">`;
}

// Profile Iterator
function profileIterator(contestants) {
    // counter
let nextIndex = 0;

// return object with next function
return {
    next: function(){
        return nextIndex < contestants.length ?
        {value: contestants[nextIndex++], done: false} :
        {done: true}
    }
};

}



function buttonSound(){
    const sound = document.querySelector('#audio');
    sound.play();
    document.querySelector(".anon").style.display = 'none'
    document.querySelector("iFrame").style.display='block';
    document.querySelector("#name").innerText=`Name: ${currentContestant.name}`;
    document.querySelector("#age").innerText=`Age: ${currentContestant.age}`;
    document.querySelector("#location").innerText=`Location: ${currentContestant.location}`;
    // document.querySelector('#imageDisplay').innerHTML = `<img
    // src="${currentContestant.image}">`;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...