未捕获的TypeError:无法读取null的属性'addEventListener'无法弄清原因

时间:2019-07-08 18:02:15

标签: javascript

在这部分代码上出现标题所示的控制台错误:

btn.addEventListener('click', () => {
    recognition.start();
});

这是JS

    const btn = document.querySelector('.talk');
const content = document.querySelector('.txt-content');

// Custom response array for Greetings
const greetings = ['I\'m doing well, thanks', 'Doing good brother!', 'Please leave me alone, not in the mood brah'];

// Custom response array for Weather 
const weather = ['The weather is fine today', 'You need a tan good sir', 'It is going to rain cats and dogs'];

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();

recognition.onstart = function () {
    console.log('voice is activated, you can speak into your microphone');
};

recognition.onspeechend = function (event) {
    const current = event.resultIndex;
    const transcript = event.results[current][0].transcript;
    content.textContent = transcript;
    readOutLoud(transcript);
};

// Add the listener to the button
btn.addEventListener('click', () => {
    recognition.start();
});

function readOutLoud(message) {
    const speech = new SpeechSynthesisUtterance();

    speech.text = 'i dont know what you said';

    // if statement for custom response array
    if (message.includes('how are you')) {
        const finalText = greetings[Math.floor(Math.random() * greetings.length)];
        speech.text = finalText;
    }

    speech.volume = 1;
    speech.rate = 1;
    speech.pitch = 1;

    window.speechSynthesis.speak(speech);
}

1 个答案:

答案 0 :(得分:-2)

这是因为btn指向null。请检查控制台btn后会得到什么。