jQuery手风琴,触发器点击会抛出错误! :object不是函数

时间:2012-02-07 17:46:16

标签: jquery html

好的有手风琴,但我没有使用jQuery UI。这是我的代码

xHTML:

<ul>
    <h2>What are your hours?</h2>
    <li>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</li>

    <h2>What are your hours?</h2>
    <li>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</li>

    <h2>What are your hours?</h2>
    <li>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</li>

    <h2>What are your hours?</h2>
    <li>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</li>
</ul>

和jquery:

$.fn.acc = function() {

  $('li').not(':first').hide();
  $('h2:first').addClass('selected'); 
    $('h2').on('click', function() {
      $('.selected').removeClass('selected');
      $(this).addClass('selected');
      var li = $(this).next('li');
      check = (li.is(':visible')) ? li.slideUp(200) : ($('li').slideUp(200))(li.slideDown(250));
  });
};
// Call the function here
$(function() {
  $('ul').acc();
});

代码正在运行,但是当您每次进入控制台时单击h2标记时都会显示以下消息:

Uncaught TypeError:object不是函数。

有人可以告诉我这是什么问题,因为代码没问题就像魅力一样。

以下是[link] 1 感谢。

2 个答案:

答案 0 :(得分:0)

在从check =开始的行上,尝试将li替换为$(li) - 仍然引用变量(而不是$('li'),但让jQuery去找它。

答案 1 :(得分:0)

这是你的代码重做更简单,有效的HTML - 更新以使用选定的课程 - http://jsfiddle.net/5HfBc/6/

HTML:

<ul>
    <li><h2>What are your hours?</h2>
        <p>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</p>
     </li>
     <li><h2>What are your hours?</h2>
        <p>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</p>
     </li>
     <li><h2>What are your hours?</h2>
        <p>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim tesque felis.</p>
        </li>


    </ul>

的javascript:

$.fn.acc = function() {
    $('li:first p').addClass("selected").show();
    $('li h2').click(function(e) {           
        $(this).siblings("p").slideToggle(200)
            .parent().addClass("selected")
            .siblings("li").removeClass("selected")
            .find("p").slideUp(200);
    });
};

$(function() {
  $('ul').acc();
});

的CSS:

ul{width:400px; margin:auto; }
li {margin: 0px; padding: 0;  text-align: left;} 
li p { display: none; }

h2 { font-size:12px; padding:0.5em; background: #e4e4e4; margin: 0px; cursor: pointer; font-weight:bold; font-size:1.5em; line-height: 2em;  border-bottom: 1px solid #c5c5c5; border-top: 1px solid #ffffff; border-radius: 5px; box-shadow: 0px 0px 0px #cdcdcd;} 
.selected h2 {background: #dcdcdc; color:black;}
h2:hover {background-color:#dcdcdc;}