我有一些试用应用程序,我尝试处理动态样式。我使用TagHelpers
从DB中撤退颜色代码并将其传递给视图。我的TagHelper
有问题:
[HtmlTargetElement(Attributes = CustomBackground)] //contains "customcolor" attribute
[HtmlTargetElement(Attributes = TheName)] //contains "customcolor" attribute
public class CustomColorTagHelper : TagHelper
{
private const string CustomBackground = "custombackground";
private const string TheName = "customcolor";
[HtmlAttributeName(TheName)]
public string TheValue { get; set; } //helpers property
[HtmlAttributeName(CustomBackground)]
public string TheBackground { get; set; } //helpers property
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var colorBack = "";
var colorStyle = "";
var styleString = "";
if (TheBackground == "one")
{
colorBack = "background-color:" + "grey" + "; "; //new color
}
if (TheBackground == "two")
{
colorBack = "background-color:" + "yellow" + "; "; //new color
}
if (TheValue == "one")
{
colorStyle = "color:" + "pink" + "; "; //new color
}
if (TheValue == "two")
{
colorStyle = "color:" + "cyan" + "; "; //new color
}
styleString = colorStyle + colorBack;
if (!output.Attributes.ContainsName("style"))
{
output.Attributes.SetAttribute("style", styleString);
}
else
{
var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == "style"); //get value of 'style'
string newAttributeValue = $"{currentAttribute.Value.ToString() + "; " + styleString}"; //combine style values
output.Attributes.Remove(currentAttribute); //remove old attribute
output.Attributes.SetAttribute("style", newAttributeValue); //add merged attribute values
}
}
}
TagHelper
正在为html对象生成样式。
我的javascript
文件正在使用适当的类将属性附加到对象:
$(document).ready(function () {
var attri = "custombackground";
var value = "one";
$(".element1").attr(attri, value);
});
问题是,在运行jquery
之后,TagHelpers
中仅剩下html
,而不是样式属性:
Index.cshtml
:
<body class="container">
<div class="element1" id="el1id">
TEST el1
</div>
<div class="element2" id="el2id">
TEST el2
</div>
<div class="element3" id="el3id">
TEST el3
</div>
<div class="element1" id="el1id">
TEST el1
</div>
<a asp-action="Edit" asp-controller="Setup">EDIT BACKGROUND COLORS</a>
</body>
</html>
然后在布局主体的末尾触发JS
文件。是否有可能在通过JS附加属性后对标签助手进行实例化?