简体   繁体   中英

Twitter Like text in jquery

I am trying to walk through a table and get a specific TD with a name of note and cut it off at 40 characters and display "..." if the text is over 40 characters.

I wrote:

var element = $('.maintenanceTable').find('td[name="note"]');
console.log(element.text().length);
if(element.text().length > 40){
    element.text().substring(0, 10) + '....';
}
console.log(element)

The first console.log shows 115 characters, the second, shows a object returned .... What am I doing wrong?

jQuery functions like "text" generally have two forms. If you supply no arguments to them (eg text() ), they give you the value contained in the element. But if you pass an argument (eg text("something") ), then it sets the value.

So you want something like this:

var element = $('.maintenanceTable').find('td[name="note"]').first();
if(element.text().length > 40) {
  element.text(
    element.text().substring(0, 39) + '...'
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM