在将用 .html() 更改的 td 之前添加图标

Prepend icon before td that will be changed with .html()

我有需要更改其值的 tds。这样做:

$(".class td:nth-child(2)").html("new value");

但我正在尝试在此值之前附加超棒的字体图标:

$(".class td:nth-child(2)").append("<i class=\"fa fa-arrow-up\"></i>");

将图标放在 html 之后。我希望它在 html 之前。看起来我需要追加,因为 html 清除了 class 信息。如何动态地将图标放在 html 之前?

改为使用 prepend() 将内容添加到父元素的开头:

$(".class td:nth-child(2)").prepend("<i class=\"fa fa-arrow-up\"></i>");

http://api.jquery.com/prepend

您需要使用.prepend():

$(".class td:nth-child(2)").prepend("<i class=\"fa fa-arrow-up\"></i>");

您始终可以使用 CSS3 并将 before/after 分配给 class,只需更改 jQuery 中的 class。

示例: Demo

在你的情况下是这样的:

//The Css
.arrow-up:before {
  display: inline-block;
  height: 25px; 
  width: 25px;
  padding-right: 5px; 
  content: '<i class=\"fa fa-arrow-up\"></i>';
}

//The jQuery
$(".class td:nth-child(2)").addClass("arrow-up");