为什么这个非常基本的JS下拉菜单不起作用

Why is this very basic JS dropdown menu not working?

本文关键字:JS 下拉菜单 不起作用 非常 为什么      更新时间:2023-09-26

它在Codepen中工作,但在本地不工作。我在同一目录中有html、css、js文件,我正在导入它们,正如您在html片段中看到的那样。有人建议我的js文件路径可能不正确,但js文件和其他文件在同一个目录中,我可以用同样的方式调用cs文件,这很有效。

我唯一能想到的是,我正在导入菜单脚本所需的不正确的jquery和jquery ui文件?

所以我的问题是为什么这个例子在这里有效http://codepen.io/WhiteWolfWizard/pen/DwKjc,但不是在我的本地机器上?

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="menuscript.js"></script>
<div class='dropdown'>
  <h1 class='title'>Select</h1>
  <ol class='drop'>
    <li>Apple</li>
    <li>Orange</li>
    <li>Banana</li>
    <li>Pineapple</li>
    <li>Mango</li>
  </ol>
</div>

CSS

.dropdown {
  position: relative;
  margin: 50px auto;
  display: table;
  font-family: sans-serif;
  font-size: 11pt;
  color: #FC3;
  line-height: normal;
  text-align: left;
  font-smoothing: antialiased;
}
.dropdown .title {
  cursor: pointer;
  height: 45px;
  padding: 0 20px;
  border-radius: 5px;
  display: block;
  box-shadow: 0 0 0 1px #FC3;
  line-height: 45px;
}
.dropdown .title:after {
  content: '';
  float: right;
  width: 0;
  height: 0;
  margin: 20px 0 0 20px;
  border-width: 5px 4px 0;
  border-style: solid;
  border-color: #FC3 transparent transparent transparent;
}
.dropdown .drop {
  position: relative;
  top: 100%;
  margin-top: 1px;
  border-radius: 0 0 5px 5px;
  display: none;
  overflow: hidden;
  box-shadow: 0 0 0 1px #FC3;
}
.dropdown .drop li {
  cursor: pointer;
  padding: 10px;
}
.dropdown .drop li:hover {
  background: #FC3;
  color: #FFF;
}
.select .title {
  border-radius: 5px 5px 0 0;
}
.select .title:after {
  transform: rotate(180deg);
}

JS

$('.dropdown .title').on('click',function(){
  $(this).parent().toggleClass('select').find('.drop').toggle();
});
$('.dropdown .drop li').on('click',function(){
  var $this = $(this), input = $this.text();
  $('.dropdown .title').text(input);
});
    enter code here

http://codepen.io/WhiteWolfWizard/pen/DwKjc

js需要在元素可用时运行。用$(函数(){})包装代码:

$(function () {
    $('.dropdown .title').on('click',function(){
        $(this).parent().toggleClass('select').find('.drop').toggle();
    });
    $('.dropdown .drop li').on('click',function(){
        var $this = $(this), input = $this.text();
        $('.dropdown .title').text(input);
    });
});