سؤال

So I have created the following code to deal with one instance of a string that requires truncating with expandable and collapsable click events.

$(document).ready(function () {
    var Element = $("[class*='truncate']");
    var FullText = $(".truncate").text();
    var Show = "<span class='show'> [...]</span>";
    var Hide = "<span class='hide'> [ ]</span>";
    var shortString = FullText.substring(0, 5);

    if (FullText.length > 5) {
        $(Element).html(shortString + Show);
    }

    $(Element).on("click", ".show", function () {
        $(Element).html(FullText + Hide);
    });

    $(Element).on("click", ".hide", function () {
        $(Element).html(shortString + Show);
    });    
});

Which truncates the following HTML

<div class="truncate">MBK-40B-FRLBBLCSLWLHBLHSLSALSAS32PDL</div>

The above code works perfectly for one instance of the class .truncate but when adding more things get a bit messy. How can I make this code work when there are many elements with this class, some of which will need to be truncated while others won't?

هل كانت مفيدة؟

المحلول

We can learn about the .each() jQuery method, here are some docs: http://api.jquery.com/each/

.each() will go through each element that was found with the selector and give you access to it through the this keyword, allowing you to run your code for one element at a time.

$(document).ready(function () {
  var Show = "<span class='show'> [...]</span>";
  var Hide = "<span class='hide'> [ ]</span>";

  $(".truncate").each(function(){
    var Element = this;
    var FullText = $(Element).text();
    var shortString = FullText.substring(0, 5);
    if (FullText.length > 5) {
      $(Element).html(shortString + Show);
    }

    $(Element).on("click", ".show", function () {
      $(Element).html(FullText + Hide);
    });

    $(Element).on("click", ".hide", function () {
      $(Element).html(shortString + Show);
    });
  });
});

There are better ways to do this, but .each() is a quick fix. What I would be concerned about is turning all those listeners off, I'm not sure what you are doing with your code later, but you don't want memory problems. Any suggestions?

نصائح أخرى

https://jsfiddle.net/5dtmm9kn/

The JS

              $('[truncate]').each(function( index ) {
                var howmuch = $(this).attr('truncate');
                var title = $( this ).text();
                var shortText = jQuery.trim(title).substring(0, howmuch)
                  .split(" ").slice(0, -1).join(" ") + " <span>...</span>";
                $( this ).html(shortText);
              });

The html

<h3 truncate="40">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h3>

The css

  [truncate] span{ 
    font-size: 0.6em;
    opacity: 0.6;
  }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top