How to append a string in table cells if and only if that table cell is not empty?
<table>
<tr>
<td>aaaa</td>
<td>bbbb</td>
</t开发者_如何学JAVAr>
<tr>
<td></td>
<td>ccccc</td>
</tr>
</table>
For above table, how can i append a string "iString" to the cell data "aaaa", "bbbb" and "cccc". But not for the empty cell.
$(document).ready(function()
{
$("table td").each(function()
{
if($.trim($(this).text()).length > 0)
{
alert("Got my td with text. appending some string");
var text = $.trim($(this).text());
text += "mystring";
$(this).text(text);
}
});
});
Here is a jsfiddle example.
The $("table td")
selector selects each td
element of the table, and the .each()
is an iterator function, which will execute the callback provided as its argument for each element that matches the selector, which are the td
elements of the table. Inside the callback, this
will refer to the td
element. The -
$(this).text().length
portion is checking to see if the text inside that td
element has a length greater than zero. If it is, then you've got a td
element with a text. The -
var text = $(this).text();
line fetches that text from the td
and assigns it to the text
variable. The next line concatenates the specified string with this variable. Finally, the -
$(this).text(text);
line assigns the concatenated string as the td
element's text.
Edit
I've added the $.trim()
function around the string-length checking to remove the white-space characters. If you want to consider the white-spaces as characters, just remove it.
$('table td').each(function() {
if($(this).text()) {
$(this).append('X');
}
});
Demo: http://jsfiddle.net/ThiefMaster/JQe2N/
Like this:
$(document).ready(function(){
$("table td").each(function(){
if($.trim($(this).html()) != '') //Remove whitespaces with $.trim
$(this).append("iString");
});
});
Hope this helps. Cheers
$('table td').each(function(){
var val = $(this).html() ;
if(val.length) {
$(this).append("yor string");
}
});
$('td').each(function(){
if ($(this).text() != "") {
$(this).append(iString);
}
});
精彩评论