我有一份员工清单,我必须得到第一个字母,第一个姓氏以该字母开头,并将其作为数据添加。
<ul class="org-list" >
<li class="org-list-item">
<span class="surname">AA</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">AB</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">AC</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">BA</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">BB</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">CA</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">CB</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">CC</span> <span class="name">John</span>
</li>
</ul>
从此列表中<li>
个姓氏为AA,BA,CA的项目应具有数据属性data-surname="A"
或data-surname="B"
,data-surname="C"
如何提取这些字母并将其作为数据添加?
我确实不知道如何启动它,所以我没有任何代码可以发布。谢谢你的帮助。
答案 0 :(得分:1)
您可以使用jQuery Data Method(DOM浏览器不可见)或只添加data-surname
属性来执行此操作。
<强> E.g。强>
$(function() {
var assignedSurname = [];
$('.org-list-item > .surname').each(function(i, elem) {
var $elem = $(elem);
var surnameInitial = $elem.text()[0];
if (assignedSurname.indexOf(surnameInitial) === -1) {
var $liParent = $elem.parent('li');
$liParent.attr('data-surname', surnameInitial);
assignedSurname.push(surnameInitial);
// Or as jquery data attribute, which is not visible to DOM browser.
//$liParent.data('surname', surnameInitial);
}
});
$('li.org-list-item[data-surname]').each(function(i, elem) {
console.log($(elem).attr('data-surname'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="org-list">
<li class="org-list-item">
<span class="surname">AA</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">AB</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">AC</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">BA</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">BB</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">CA</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">CB</span> <span class="name">John</span>
</li>
<li class="org-list-item">
<span class="surname">CC</span> <span class="name">John</span>
</li>
</ul>
如果您选择使用jQuery数据属性,则可以通过
访问DOM的值$('li.org-list-item[data-surname]').each(function (i, elem){
console.log($(elem).data('surname'));
});
答案 1 :(得分:0)
这是一个快速的功能,可以帮助你。
var selector = 'ul.org-list-item li span.surname'
Array.prototype.slice.call(
document.querySelectorAll(selector)
).forEach(function(item) {
var firstLetter = item.textContent.slice(0,1);
item.parentElement.setAttribute('data-surname',firstLetter);
});
的信息: