asp.net-core - 如何获取css隔离随机字符串

标签 asp.net-core jquery-selectors razor-pages asp.net-core-css-isolation

我使用 CSS 隔离。
这是输出的 html 代码:

<div b-1yc1hoca3 class="test">Text</div>
.test {
    border: 1px solid red;
}

CSS隔离生成的随机字符串是:b-1yc1hoca3
我在页面加载后添加了一些 html 代码。

$('#main').append(`<div class="test">Text</div>`);

添加上述代码时,上述代码没有 CSS 隔离随机字符串 (b-1yc1hoca3),CSS 代码不适用于该元素。
如何使用 JQuery 获取 CSS 隔离随机字符串以添加到以下代码:

$('#main').append(`<div class="test">Text</div>`);

我唯一需要的是b-1yc1hoca3
例如

var cssIsolationRandomString = $('.test').attr('cssIsloationRandomString');
$('#main').append(`<div ${cssIsolationRandomString} class="test">Text</div>`);

据我所知,所有CSS隔离随机字符串都以b-开头。

问题是 CSS 隔离随机字符串 是随机字符串,我不知道如何获取以 b-

开头的随机属性

最佳答案

首先,我找到了一个github issue这里提到CSS隔离是一个构建时过程,隔离字符串是generated by framework .

Within the bundled file, each component is associated with a scope identifier. For each styled component, an HTML attribute is appended with the format b-{STRING}, where the {STRING} placeholder is a ten-character string generated by the framework.

因此,我们不能使用Jquery生成随机字符串并在附加动态内容时使用它。但我发现页面渲染时页面中的随机字符串是一样的。因此,当我们附加动态内容时,我们可以首先从初始存在的 DOM 元素中获取 b-{string} ,然后在新内容中使用它,这对我有用。

enter image description here

<div id="dynamicContent">
    <p id="targetItem">hello this is content in red</p>
</div>
<button id="add">add section</button>

@section Scripts{
     <script>
        $("#add").click(function(){
            var attrs = document.getElementById("targetItem").attributes;
            console.info(attrs);
            var isolation = "";
            $.each(attrs,function(i,elem){
                if (elem.name.startsWith("b-")){
                    isolation = elem.name;
                }
            });
            $('#dynamicContent').append("<p "+isolation+" >added content</p>");
        })
    </script>
}

enter image description here

关于asp.net-core - 如何获取css隔离随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75209175/

相关文章:

c# - ASP.NET 核心 SPA SSR : Use AntiForgery

live 函数内的 jquery 变量不起作用

c# - 如何从 Razor Page 获取 Azure 数据表 ETag 值

asp.net-mvc - 使用 Jquery/Ajax 将模型传递到 Controller

c# - 如何简单地从 appsettings.json 读取

javascript - 比较数据选择器中的值

c# - 如何在 asp.net Core Razor Pages 中填充复选框列表?

c# - 依赖项注入(inject) ASP.NET Identity 用户(和单元测试)

visual-studio-2015 - ASP.NET 5、Entity Framework 7 和 SQL Server 2014 - 多个 dbContexts、SQL View

javascript - 这个选择器是如何工作的?