My project is the blazor web app (.net 9.0)
.razor code :
<div>
<ul class="nav nav-tabs marginBottom" id="myTab">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#profile">
测试页1
<span class="closeTabBtn">×</span>
</a>
</li>
</ul>
</div>
<div>
<div class="operationDiv">
<button type="submit" class="btn" id="composeButton">Compose</button>
</div>
</div>
.css code :
.closeTabBtn{
background-color:gray;
color:black;
}
javascript code :
$('#composeButton').click(function (e) {
e.preventDefault();
$('.nav-tabs').append('<li class="nav-item"><a class="nav-link" href="#1">测试页<span class="closeTabBtn">×</span></a></li>');
});
Why are tags added through the append method missing CSS styles ?
The format b-{STRING}
is appended by CSS isolation bundling during build time process, it is before dynamic append elements via the button click event. So, you can't find them in the dynamic append content.
To solve this issue, when we append the dynamic content, we can first to get the b-{string}
from the initial existed DOM element (first li), then use it in the new content, the follow code worked for me:
App.razor page:
<script>
function appendli() {
var attrs = $("#myTab").find('li')[0].attributes;
console.info(attrs);
var isolation = "";
$.each(attrs,function(i,elem){
if (elem.name.startsWith("b-")){
isolation = elem.name;
}
});
$('.nav-tabs').append('<li '+ isolation +' class="nav-item"><a class="nav-link" '+ isolation +' href="#1">测试页<span '+ isolation +' class="closeTabBtn">×</span></a></li>');
};
</script>
Razor component/page
@page "/appendtest"
@rendermode InteractiveServer
@inject IJSRuntime JS
<h3>AppendTest</h3>
<div>
<ul class="nav nav-tabs marginBottom" id="myTab">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#profile">
测试页1
<span class="closeTabBtn">×</span>
</a>
</li>
</ul>
</div>
<div>
<div class="operationDiv">
<button type="submit" class="btn" id="composeButton" @onclick="AppendLi">Compose</button>
</div>
</div>
@code {
private async Task AppendLi() {
await JS.InvokeVoidAsync("appendli");
}
}
After running the application, the result as below: