如何使用.each

时间:2015-08-04 10:48:48

标签: javascript jquery html each labels

我想编写一个脚本,如果长度超过30个字符,将调整标签长度,但找不到它保持不变的原因。 的jsfiddle: http://jsfiddle.net/rokas_m/9g3bcamz/10/

HTML:

<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>

<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />

jQuery的:

$('label').each( function(){ 
    var string = $(this).text();
    var ilgis = $(this).text().length;
   if (ilgis > 30){
   var string = string.substr(0,17)+'...';
     $( 'label' ).innerHTML = string;
        console.log(string);
   }

}
);  

3 个答案:

答案 0 :(得分:3)

您可以使用.text()通过传递一个回调函数作为其参数来设置值,该参数将为每个标签调用,例如

&#13;
&#13;
$('label').text(function(i, text) {
  return text.length > 30 ? text.substr(0, 17) + '...' : text;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>

<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
&#13;
&#13;
&#13;

或者

&#13;
&#13;
$('label').each(function() {
  var string = $(this).text();
  var ilgis = string.length; //reuse the variable
  if (ilgis > 30) {
    string = string.substr(0, 17) + '...';
    $(this).html(string);//$(...) returns a jQuery object so don't have `innerHTML` property, also you need to target the current `label` not all of them
    //or just
    //this.innerHTML = string
    console.log(string);
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>

<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将此$( 'label' ).innerHTML = string;替换为$(this).html(string);

以下是修改过的代码:

$('label').each( function(){ 
    var string = $(this).text();
    var ilgis = $(this).text().length;
    if (ilgis > 30){
      var string = string.substr(0,17)+'...';
      $(this).html(string);
    }
   }
);

答案 2 :(得分:1)

参考此

$('label').each( function(){ 
    var string = $(this).text();
    var ilgis = $(this).text().length;
   if (ilgis > 30){
   var string = string.substr(0,17)+'...';
     jQuery(this).html(string);
        console.log(string);
   }

}
);