个人关于dataset的用法一些总结

操作dataset方法的,必须是DOM对象,jQuery对象不能使用.具体看代码

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

<head>
    <title>dataset的用法</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <input type="text" data-id="userid" id="btn">
    <div id="meal" data-drink="coffee" data-food="sushi" data-meal="lunch" data-url="https://www.baidu.com">随便来呀</div>


    <a href="" id="test" target="_blank">测试一下哈</a>
</body>

</html>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script>
    $(function () {
        var $test = $("#test");
        var $meal = $("#meal");
        $meal.on('click', function () {
            console.log(this);

            console.log($(this));
            console.log($meal);

            console.log($(this)[0])
            console.log($meal[0]);

            $test.attr('href', $meal[0].dataset.url);
            //$test.attr('href', this.data('url'));// 报错 this.data is not a function
        //正确用法:
$test.attr('href', $(this).data('url'));

}) }); // dataset方法,只能是DOM对象才能操作,jquery对象不能使用, //如果是用jQuery获取的,则需要用[index]或者get[index]转换为DOM对象 //而data()方法也可以达到上面的目的,但是data()方法是jQuery方法,所以使用他的时候必须是jQuery对象 </script>

  

原文地址:https://www.cnblogs.com/lxk0301/p/7009788.html