如何使用Jquery插件开发显示和隐藏段落?

时间:2017-01-12 10:22:57

标签: javascript jquery html jquery-plugins

我盯着编写Jquery插件,并尝试学习Jquery插件开发最佳实践。

我需要做的是当我点击more需要显示完整内容时,如果再次点击则隐藏它。你能不能帮我做。



(function() {

  $.fn.textCounter = function(className, textCount) {

    return this.each(function() {
      var title = $('.' + className).text();
      if (title.length > textCount) {
        var content = title.substr(0, textCount) + ' ....';
        $('.' + className).text(content).append('<span  class="showcontent">More <i class="fa fa-angle-down" aria-hidden="true"></i></span>');
      } else {
        $('.' + className).text(title);
      }

    });
  };

}());
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>jQuery Word/Text Counter Plugins</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


</head>

<body>




  <!-- Start second row -->

  <section class="details-row-second">

    <div class="container content-box">

      <div class="col-xs-12 col-sm-6 col-md-6">
        <h2>WHO WE ARE ?</h2>
        <p class="contentClass">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
      </div>
      <div class="hidden-xs  col-sm-6 col-md-6">

      </div>

    </div>

  </section>


</body>

<script type="text/javascript">
  $(document).ready(function() {
    $(".contentClass").textCounter('contentClass', '300');
  });
</script>



</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

不要将数字作为字符串发送:

$(".contentClass").textCounter('contentClass', 300);

因为在您的插件中,您要将数字与字符串进行比较:

if (title.length > textCount) {

此处title.length的类型为数字,textCount为字符串,现在为数字。