js实现页面跳转,自定义属性,id和class的操作,innerHTML

js实现页面跳转

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="fn()">百度</button>
    <script>
        function fn(){
            // location.replace('http://www.baidu.com')
            // location.href = 'http://www.baidu.com'
            window.open('http://www.baidu.com')
        }
    </script>
</body>
</html>

自定义属性


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <ul>
        <li index="1">首页</li>
        <li index="2" class="ac">列表</li>
        <li index="3">详情</li>
        <li index="4">关于</li>
    </ul>
    <script>
        var ac = document.querySelector('.ac')
        // 这样是取不到的,因为index是自定义的而不是标准里的
        // console.log(ac.index)
        // getAttribute用来获取自定义属性
        var index = ac.getAttribute('index')
        console.log(index)

        // 设置自定义属性
        // 自定义属性的名称可以随便写,但是w3c推荐用 data- 
        // 自定义属性设置无论什么类型的值,最后获取统一都是字符串
        ac.setAttribute('data-id',true)

        // 删除自定义属性,属性名和属性值都没了
        ac.removeAttribute('index')
    </script>
</body>

</html>


id和class的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="fn()">按钮</button>
    <div id="box" class="box section">box</div>
    <script>
        var div = document.querySelector('#box')
        function fn(){
            // div.id = 'box1'
            // div.className = 'box2' // 这种写法是box2把原来的box直接覆盖
            // div.className = 'box box2'
            div.className += ' box2'

            // classList仅支持IE8+

            // 添加一个class
            div.classList.add('ac')

            // 移出一个class,如果要移出多个,那就分两次写
            div.classList.remove('section')

            console.log(div.className)
            console.log(div.classList)
            console.log(div.classList[0])
            console.log(div.classList[1])
        }
    </script>
</body>
</html>


innerHTML


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="fn()">按钮</button>
    <div id="box" class="box section">box</div>
    <script>
        var div = document.querySelector('#box')
        function fn(){
            // div.innerHTML = 'box2'
            // 会解析标签
            // div.innerHTML = '<b>box3</b>'
            // 就不会解析标签(相当于在div里面添加文本内容)
            div.innerText = '<b>box3</b>'

        }
    </script>
</body>

</html>
发布了60 篇原创文章 · 获赞 3 · 访问量 529

猜你喜欢

转载自blog.csdn.net/dfc_dfc/article/details/105550005
今日推荐