将Javascript代码转换为jquery时出现问题

时间:2019-01-17 09:57:25

标签: javascript jquery

我是jquery新手,我想将下拉菜单的以下javascript代码转换为jquery

var dropdown = document.getElementsByClassName("dropdown-btn");

var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    this.classList.toggle("active1");
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.display = "block";
    }
  });
}

到目前为止,我的代码是

$(".dropdown-btn").each( function() {
   $(this).click(function () {
     var dropdownContent = $(this).parent().next();
     dropdownContent.show();
     alert(dropdownContent.val());
     alert("jquery.....");
  });
});

以下是HTML代码:

<button class="dropdown-btn">1</button>
<div class="dropdown-container">
    <a href="" target="_blank">1</a>
    <a href="" target="_blank">2</a>
    <a href="" target="_blank">3</a>
</div>

<button class="dropdown-btn">2</button>
<div class="dropdown-container">
    <a href="" target="_blank">3</a>
    <a href="" target="_blank">1</a>
    <a href="" target="_blank">2</a>
</div>

1 个答案:

答案 0 :(得分:1)

看看并告诉我是否可行。

$(".dropdown-btn").click(function () {
  $(this).toggle("active1");
  var dropdownContent = $(this).next();
  $(dropdownContent).toggle();
});