JQuery intercepts string code of specified length

  • 2020-03-30 03:44:19
  • OfStack

Example, intercepting string code.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>jQuery Intercept string operation ---www.jb51.net</title> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
font-family:" Song typeface ", Arial, Helvetica, sans-serif; 
border:1px solid #ccc; 
margin:60px auto 0; 
padding:10px 0 0 10px 
<script type="text/javascript"> 
var self = $("div[limit]"); 
var objString = $(this).text(); 
var objLength = $(this).text().length; 
var num = $(this).attr("limit"); 
if(objLength > num){ 
objString = $(this).text(objString.substring(0,num) + "..."); 
<div id="best"> 
<div limit="12"> Calculates the length of the string </div> 
<div limit="10"> There's an optimization on this side that's very public on this side </div> 
<div limit="12"> There's an optimization over here that has a very open length and a very open length </div> 
<div limit="12"> Calculate the length of the word </div> 
<div limit="10"> There's a lot of optimization on this side there's a lot of optimization on this side there's a lot of optimization on this side there's a lot of optimization on this side </div> 

The above code implements the function of intercepting strings.

I. realization principle

Get the length of the text in div and compare it to the length specified by the attribute and limit. Alternative.

Two. Code comments

JQuery. Fn.limit =function(){}, which extends an instance function for jQuery. JQuery objects can call this function.
Var self = $("div[limit]") to get a collection of div objects with a limit property.
3. Self.each (function(){}, can be obtained by making each object in the div object collection walk through the specified function once.
Var objString = $(this).text(), which gets the text in the div element, while the each() function iterates over the current div.
Var objLength = $(this).text().length, which gets the length of the text in the current div.
Var num = $(this).attr("limit"), gets the value of the limit property in div, used here as the specified character length.
7. The if (objLength > Num){},div text length greater than the specified length this executes the specified code.
$(this).attr("title",objString), sets the value of the title property of div to the content in div.
9. ObjString = $(this). Text (objstring.substring (0,num) + "..." ), intercepts a string of the specified length and replaces any that exceed it with an ellipsis.

Related articles: