从JavaScript转换为

时间:2016-08-07 19:08:35

标签: javascript jquery html

我在将代码从JavaScript转换为jQuery时遇到问题。这是来自W3Schools的示例代码,用于创建下拉按钮。

// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};

/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

如果您try jQuery,则代码很容易理解。

// Execute the code when the document is ready.
$(document).ready(function () {
  /* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
  function myFunction() {
    // This one removes the class "show" from the matched set of elements.
    $(".dropdown-content").removeClass("show");
    // This one toggles the class "show" on the matched set of elements.
    $("#myDropdown").toggleClass("show");
  }

  // Get the button, and when the user clicks on it, execute myFunction
  $("#myBtn").click(myFunction);
});

我不认为这是代码转换的问题。我坚信W3Schools已经错误地使用了重复的id值。