【问题标题】:Why is querySelector() returning null even though the class does exist?为什么即使类确实存在 querySelector() 返回 null?
【发布时间】:2019-01-27 18:31:05
【问题描述】:

我阅读了有关此内容的信息,但查询选择器似乎没有找到该类。因此,返回 null。 我尝试了这里提供的最后一个解决方案: document.querySelector(…) is null error 并且控制台没有给出任何错误。然而,什么也没有发生。正在努力

cosole.log(document.querySelector('wordImage');

不向控制台显示任何消息。

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <style>
        .exa-title{
            font-style: italic;
            margin-left:10px;
            color: dimgray;
        }
    </style>
    <body>
        <img class="word-image"src="" alt="">
        <span class="ex-title"></span><span class="ex-sentence"></span>
        <input class="word-input" type="text" name="" autofocus>

<script>

window.addEventListener('load', init);

    const vocabularyList = [
      {
        image: "https://media.istockphoto.com/photos/red-apple-with-leaf-isolated-on-white-background-picture-id185262648?k=6&m=185262648&s=612x612&w=0&h=u9rMspGGTOkgUSzZ6INtT_Ww4NpGz9zHMGRmIJJjBqQ=",
        word: "apple",
        example: "The red apple."
      },
      {
        image: "https://upload.wikimedia.org/wikipedia/commons/8/88/Bright_red_tomato_and_cross_section02.jpg",
        word: "tomato",
        example: "The red tomato."
      }
    ];

function init(){
    //DOM  variables
    const wordImage = document.querySelector('word-image');
    const ex_title = document.querySelector('ex-title');
    const ex_sentence = document.querySelector('ex-sentence');
    const wordInput = document.querySelector('word-input');
    // Load the first object from the array
    showCard(vocabularyList);
    //Start matching on word input
    wordInput.addEventListener('input', matchWords);
}
// Pick and show random word

function showCard(vocabularyList){
    //Generate random array index
    const randIndex = Math.floor( Math.random() * vocabularyList.length);
    //Output the random word
    wordImage.src = vocabularyList[randIndex].image;

}

function matchWords(){
    if(wordInput.value === vocabularyList[randIndex].word){
        // ex_title.innerHTML = "p. ej.";
        ex_sentence.innerHTML = vocabularyList[randIndex].example;
    }
}

</script>


    </body>
</html>

【问题讨论】:

    标签: javascript null jquery-selectors


    【解决方案1】:

    querySelector 接受 CSS 选择器。此代码使用 tag 选择器:

    const wordImage = document.querySelector('word-image');
    

    也就是说,它会查找标签为word-image的元素,如下所示:

    <word-image>...</word-image>
    

    class 选择器以 . 开头:

    const wordImage = document.querySelector('.word-image');
    

    见:

    【讨论】:

    • 我不敢相信我没有注意到这一点。但是在正确选择类后它仍然为空。
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2019-09-24
    • 2018-11-12
    • 1970-01-01
    • 2021-02-07
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多