简体   繁体   English

循环遍历foreach循环中的元素并从值中提取首字母缩写词,然后将另一个元素的值设置为派生的首字母缩略词

[英]Loop through an element in the foreach loop and extract the acronym from the value and then set another element's value to the derived acronym

I'm having this challenge of looping through an element in a foreach iteration and then extract an acronym from the element, then set another element's value to the derived acronym. 我正在接受在foreach迭代中循环遍历元素然后从元素中提取首字母缩略词的挑战,然后将另一个元素的值设置为派生的首字母缩略词。

Here's my code 这是我的代码

1) cshtml: 1)cshtml:

foreach (var item in Model)
{                
     <h3 class="getName">@item.FullName</h3>
     [...]
     <h4 class="displayAvatar"></h4>
     [...]
}   

2) Jquery code: 2)Jquery代码:

$('.getName').each(function (e) {
        var techieFullName = $('.getName').text();
        var getNameAcronym = techieFullName.match(/\b(\w)/g);
        var theName = getNameAcronym.join('');
        $('.displayAvatar').text(theName);
});

The code above assigns the same result(derived acronym) to all h4 elements with class of "displayAvatar" but i want each fullname be set to each acronym 上面的代码将相同的结果(派生的首字母缩略词)分配给具有“displayAvatar”类的所有h4元素,但我希望每个全名都设置为每个首字母缩略词

How do i get it running please? 我如何让它运转好吗? Appreciate 欣赏

Since your using a forEach Loop. 因为你使用了forEach循环。 Its easier if you enclose multiple heading tags inside a div say eachRow . 它容易,如果您奉上内的多个标题标签diveachRow script is provided below, its straight forward. 脚本提供如下,其直截了当。

CSHTML: CSHTML:

foreach (var item in Model)
{     
   <div class="eachRow">           
     <h3 class="getName">@item.FullName</h3>
     <h4 class="displayAvatar"></h4>
   </div>
}  

JQUERY: JQUERY:

$('.getName').each(function (e) {
        var techieFullName = $(this).text();
        var getNameAcronym = techieFullName.match(/\b(\w)/g);
        var theName = getNameAcronym.join('');
        $(this).closest('.eachRow').find('.displayAvatar').text(theName);
});

Edit: Use pipe lining to reduce the use of many local variables. 编辑:使用管道衬里减少许多局部变量的使用。

$('.getName').each(function (e) {
            var result=  $(this).text().match(/\b(\w)/g).join('');
            $(this).closest('.eachRow').find('.displayAvatar').text(result);
    });

You can use .next() to get the immediately following sibling with class displayAvatar : 您可以使用.next()来获取类displayAvatar的紧随其后的兄弟:

$('.getName').each(function (e) {
    var techieFullName = $(this).text();
    var getNameAcronym = techieFullName.match(/\b(\w)/g);
    var theName = getNameAcronym.join('');
    $(this).next(".displayAvatar").text(theName);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM