gpt4 book ai didi

jquery - 从具有多个类的 div 中选择一个类并将其添加为 id?

转载 作者:行者123 更新时间:2023-11-28 03:49:41 25 4
gpt4 key购买 nike

我正在尝试从具有多个类的 div 中选择一个类并将其打印为 id。

当前代码:

<div class="name  usrname1  views-row">
<div class="views-field views-field-field-user-name">
<div class="field-content">John</div>
</div>
</div>
<div class="name usrname2 views-row">
<div class="views-field views-field-field-user-name">
<div class="field-content">Jane</div>
</div>
</div>

在这段代码中,我需要创建“usrname1”并使其成为 id。该类会动态变化并且是唯一的。

我需要什么:

<div class="name  usrname1  views-row" id="usrname1">
<div class="views-field views-field-field-user-name">
<div class="field-content">John</div>
</div>
</div>
<div class="name usrname2 views-row" id="usrname2>
<div class="views-field views-field-field-user-name">
<div class="field-content">Jane</div>
</div>
</div>

https://jsfiddle.net/farhanmae/agx6t0wy/1/

最佳答案

这是我能找到的最佳解决方案。

遍历所有 div 搜索具有类 usrnamediv。找到后,将其添加到所选 div

id

$(document).ready(function() {
/* Loop through all divs */
$("div").each(function() {
var divElem = $(this) ;
var cls = $(this).attr("class") ; //Get the div classes

/* If class has the string "usrname" */
if (cls.indexOf("usrname") !== -1) {
var clsArr = cls.split(" ") ; //Split the cls string into an array holding all the classes.

/* Loop through the array */
clsArr.forEach(function(clsName) {
/* If class has the string "usrname" */
if (clsName.indexOf("usrname") !== -1) {
divElem.attr("id", clsName) ; //Add the class to the id of the selected div
}
});
}
}) ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="name usrname1 views-row">
<div class="views-field views-field-field-user-name">
<div class="field-content">John</div>
</div>
</div>
<div class="name usrname2 views-row">
<div class="views-field views-field-field-user-name">
<div class="field-content">Jane</div>
</div>
</div>

关于jquery - 从具有多个类的 div 中选择一个类并将其添加为 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47528816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com