javascript 限制 div 中的字符数具有特定的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4448856/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limiting the no of characters in a div has specific class
提问by Ra.
I have some set of div which has a class name. Here i want to control/limit the no of characters to be displayed in the div based on the class name using javascript.Please help me to fix this.
我有一组具有类名的 div。在这里,我想根据类名使用 javascript 控制/限制要在 div 中显示的字符数。请帮我解决这个问题。
回答by chiborg
Here is the jQuery solution for limiting the elements with .myclassto 200 chars: 
这是将元素限制.myclass为 200 个字符的 jQuery 解决方案:
var myDiv = $('.myclass');
myDiv.text(myDiv.text().substring(0,200));
The pure JavaScript solution (for all browsers that don't support getElementByClassname) would look like this:
纯 JavaScript 解决方案(适用于所有不支持 的浏览器getElementByClassname)将如下所示:
var i;
var divs = document.getElementsByTagName('div');
for(i=0;i<divs.length;i++) {
  if(divs[i].className == 'myclass') {
    divs[i].innerHTML = divs[i].innerHTML.substring(0,200);
  }
}
Note that the pure JavaScript method may create invalid HTML if the divs contain markup. The correct way would be to iterate over the child nodes in the div.
请注意,如果 div 包含标记,纯 JavaScript 方法可能会创建无效的 HTML。正确的方法是遍历 div 中的子节点。
回答by Adamski
Use the substring() method in javascript,
使用 javascript 中的 substring() 方法,
details on usage here
使用详情请看这里
http://www.w3schools.com/jsref/jsref_substring.asp
http://www.w3schools.com/jsref/jsref_substring.asp
good luck.
祝你好运。
if you are using jQuery select by the class and run the sub string method.
如果您使用 jQuery 按类选择并运行子字符串方法。
回答by Pebbl
a version that honours existing child elements
尊重现有子元素的版本
Came across this Q&A but was looking for something that wouldhandle child elements correctly, rather than just a sub-string slice. For those that may need this, here is what I put together. Basically it recursively steps through child elements, clones and appends them to a new container — all the while totaling up the number of "words" it finds (i.e. text content split by spaces).
碰到这个Q&A,但一直在寻找的东西,会正确处理的子元素,而不仅仅是一个子串片。对于那些可能需要这个的人,这是我放在一起的。基本上它递归地遍历子元素,克隆它们并将它们附加到一个新容器中——同时总计它找到的“单词”的数量(即由空格分割的文本内容)。
Once it reaches it's word limit it will stop processing/appending new nodes. If the content of the final text node will breach the word limit, the node's text value is sliced to meet the requirement.
一旦达到它的字数限制,它将停止处理/附加新节点。如果最终文本节点的内容将超出字数限制,则对节点的文本值进行切片以满足要求。
The code expects the class name provided to be the containing element of mainly text nodes with some other elements mixed in. For example, wrapping-elementwould be the element to target:
代码期望提供的类名是主要文本节点的包含元素,并混合了一些其他元素。例如,wrapping-element将是要定位的元素:
<p class="wrapping-element">
  Rude alert! An electrical fire has knocked out my voice-recognition unicycle!
  Many Wurlitzers are <strong>missing from my database!</strong> 
  <a href="#shop">Abandon shop!</a>
  This is not a <i>daffodil!</i>
</p>
the code
代码
I've tried to keep this a succinct as possible, it works in all modern browsers — mainly those that support getElementsByClassNameand cloneNode:
我尽量保持简洁,它适用于所有现代浏览器——主要是那些支持getElementsByClassName和cloneNode:
var wordlimit = (function(){
  var clonempty = function( elm ){
    var doppel = elm.cloneNode();
        doppel.innerHTML = '';
    return doppel;
  };
  var wordsmith = function( elm, out, opts ){
    var i, l, kids = elm.childNodes, kid, txt, wrd, tnd;
    for (i=0, l=kids.length; i<l && opts && opts.limit; i++) {
      if ( (kid = kids[i]) && kid.nodeType === 1 ) {
        wordsmith( kid, out.appendChild( clonempty(kid) ), opts );
      }
      else if ( kid && kid.nodeType === 3 ) {
        txt = kid.nodeValue;
        wrd = txt.replace(/^\s+|\s+$/g, '').split(' ');
        if ( wrd.length >= opts.limit ) {
          tnd = document.createTextNode( wrd.slice(0, opts.limit).join(' ') );
          out.appendChild( tnd );
          opts.limit -= wrd.length;
          if ( opts.limit < 0 && opts.ellipsis ) {
            out.appendChild( document.createTextNode('...') );
          }
          opts.limit = 0;
        }
        else {
          opts.limit -= wrd.length;
          out.appendChild( document.createTextNode(txt) );
        }
      }
    }
    return out;
  }
  return function(classname, limit, ellipsis){
    var i, l, elms = document.getElementsByClassName(classname), elm, out;
    for (i=0, l=elms.length; i<l; i++) {
      elm = elms[i];
      out = wordsmith( elm, clonempty(elm), {
        limit: limit, 
        ellipsis: ellipsis
      });
      elm.parentNode.insertBefore( out, elm );
      elm.parentNode.removeChild( elm );
    }
  };
})();
Usage
用法
To call is quite simply:
调用很简单:
wordlimit(class-name :string, word-limit :int, add-ellipsis :boolean)
so:
所以:
wordlimit('wrapping-element', 40, true)
Disclaimer
免责声明
The above could be improved to support complex CSS selectors, or just allow the provision of the actual element(s) to work with. The current version does support multiple elements with the specified class name.
以上可以改进以支持复杂的 CSS 选择器,或者只允许提供实际元素来使用。当前版本确实支持具有指定类名的多个元素。
Please note:This code will remove the original element, and replace with a newly fashioned clone. Because the code relies on cloneNode, any event listeners that are already in place will be lost, as per this snippet from the linked MDN page:
Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g. node.onclick = fn).
It goes without saying that any existing live element references to the elements being modified by this code will also be broken. [Why mention it then? Ed.]
I had no need to worry about keeping the existing elements, but if you require this it should be quite simple to rewrite the code to work on existing elements; rather than clone and destroy.
请注意:此代码将删除原始元素,并替换为新样式的克隆。由于代码依赖于cloneNode,任何已经存在的事件侦听器都将丢失,根据链接的 MDN 页面中的这个片段:
克隆节点会复制其所有属性及其值,包括内在(内联)侦听器。它不会复制使用 addEventListener() 添加的事件侦听器或分配给元素属性的事件侦听器(例如 node.onclick = fn)。
不言而喻,对被此代码修改的元素的任何现有活动元素引用也将被破坏。【那为什么要提呢?编辑]
我不必担心保留现有元素,但如果您需要这样做,重写代码以处理现有元素应该非常简单;而不是克隆和破坏。

