带有data-id的onclick有任何错误吗?

时间:2018-07-12 17:41:14

标签: javascript

我的代码有什么错误吗?我想每次使用data-id单击按钮时都显示/隐藏该部分,因为我有不同的部分:

function myFunction() {
    var foo = $("section").data("id");
    if (foo.style.display === "none") {
        foo.style.display = "block";
    } else {
        foo.style.display = "none";
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="myFunction()">Try it</button>
    
<section data-id="mySection">
    This is my Section element.
</section>

3 个答案:

答案 0 :(得分:1)

您可以尝试使用Document.querySelector()

document.querySelector('section[data-id=mySection]')

function myFunction() {
  var foo = document.querySelector('section[data-id=mySection]');
  if (foo.style.display === "none") {
    foo.style.display = "block";
  } else {
    foo.style.display = "none";
  }
}
<button onclick="myFunction()">Try it</button>

<section data-id="mySection">
  This is my section element.
</section>
<section>
  This is another section.
</section>

答案 1 :(得分:1)

您可以使用id属性代替data-id

function myFunction() {
    var foo = $("#mySection"); //use the id selector
    // but if you need to use the data-id attribute you can do this
    // var foo = $("section[data-id=mySection]");

    if (foo.css("display") === "none") { //then you can use jquery's css() function
        foo.css("display", "block");
    } else {
        foo.css("display", "none");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="myFunction()">Try it</button>
    
<section id="mySection">
    This is my Section element.
</section>

答案 2 :(得分:1)

如果要定位元素,则

$('section[data-id="mySection"]')是选择器。

$('button').on('click', myFunction);

function myFunction() {
    var $elem = $('section[data-id="mySection"]');
    
    $elem.toggle($elem.is(':hidden'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Try it</button>

<section data-id="mySection">
    This is my Section element.
</section>