简体   繁体   中英

how to change font dynamically in table cell using jquery

On a user event I am dynamically building a html table in a pop window in my code I have the following line that builds the table row cells:

$("<td BGCOLOR='#F9ED6E'><font color='#ff2500'></font></td>").text(object[property]).appendTo(row);

This does change the background color but it does not change the font color is there a way to rewrite this statement above to allow also changing the font color? I suspect somehow that .text(object[property] needs to go after the "font color='#ff2500'" part but I'm not certain how to do that?

Well my jQuery isn't so great. So I can show you a way to do it with plain old javascript. This would be considered kind of a dirty way to do it. But it should work just fine.

row.innerHTML = "<td BGCOLOR='#F9ED6E'><font color='#ff2500'>" + object[property] + "</font></td>";

Now I'm sure someone could tell you a good way to do a similar thing in jQuery. Also, if I were doing this "more properly" I'd create actual DOM elements in js and append them to the row. But I thought this might be easier to understand as it uses the same sort of technique you were using. And it'll work just fine.

UPDATE: The Proper Method
But still vanilla javascript

var eCell;
eCell = document.createElement("td");
eCell.style.backgroundColor = "#F9ED6E";
eCell.style.color = "#ff2500";
eCell.innerHTML = object[property];

row.appendChild(eCell);

The easiest way would be using CSS.

td {color:#fff}

Then you won't need to use a Font tag, and the text inside will be white. By the way, I don't see you are typing anything inside the table.

I will recommend you to use a class for all the styles and insert them as a property of the 'td'. Lets imagine that you have a div where you want to add those td elements you need to get that element and then add the td. Here is an example how you acomplish that. Is very simple but can give you and idea

$(document).ready(function(){
  $("button").on('click', function(event) {
    event.preventDefault();
    /* Act on the event */
    $("#myDiv").append("<td class='background'></td>");
  });
});

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