【问题标题】:Document.querySelector() doesn't work with bootstrap cssDocument.querySelector() 不适用于引导 css
【发布时间】:2021-03-10 21:08:39
【问题描述】:

HTML

<html lang="en">

<head>

    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="firstapp.js"></script>
</head>

<body>

    <div id="buttons">
        <h1>Hello</h1>
        <h2>0</h2>
        <button class="btn btn-primary" type="submit">Hello</button>
        <button class="button2">count </button>
    </div>

</body>

</html>

Javascript

let x = 0

function counter() {
    x++;
    document.querySelector('h2').innerHTML = x;
    if (x % 10 === 0) {
        alert(`counter is now ${x}`);

    }
}
document.addEventListener("DOMContentLoaded", function() {
    document.querySelector('.button2').onclick = counter; //This statement is for counter function 
    document.querySelector('.btn btn-primary').onclick = function() { //This is Hello Function 
        let heading1 = document.querySelector('h1');

        if (heading1.innerHTML === "Hello!!") {
            heading1.innerHTML = "Goodbye!!";
            //document.querySelector('.btn btn-outline-secondary').innerHTML = 'goodbye';
        } else {
            heading1.innerHTML = "Hello!!";
            //document.querySelector('.btn btn-outline-secondary').innerHTML = 'Hello!!';
        }


    };
})

当我使用本地 css 文件 Document.queryselector 时,它工作得很好,但是一旦我链接引导类,Java 脚本就无法识别任何引导类并给出错误“TypeError:无法设置属性'onclick'为空 在 HTML 文档。 "

【问题讨论】:

    标签: javascript html css bootstrap-4


    【解决方案1】:

    在 JavaScript 中,使用 CSS 选择器 选择元素,而不是 HTML 语法。
    改变

    document.querySelector('.btn btn-primary')
    

    document.querySelector('.btn.btn-primary')
    

    表示具有两个类名的元素。通过将空格更改为点,对其余部分进行类似操作。

    【讨论】:

      【解决方案2】:

      在 primay 按钮中为 ex 'pbtn' 添加新类并替换它 document.querySelector('.btn btn-primary')

      有了这个

      document.querySelector('.btn.btn-primary')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多