我有类名称Style1,Style2样式的Html ....我想根据我在静态HTML中指定的类定义来分配id。我想在动态部分中分配Id。我没有任何我希望通过jQuery分配的Dyanmic HTML访问权限。
静态类名称部分。
<div id="mediafarmplugin">
<div class="style1">Get External Content</div>
<div class="style2">Get External Content</div>
<div class="style3">Get External Content</div>
<div class="style4">Get External Content</div>
<div class="style...">......</div>
</div>
基于班级名称样式的动态分配ID
<div id="table">
<div id="style1">Style1 appear</div>
<div id="style2">Style2 appear</div>
<div id="style3">Style3 appear</div>
<div id="style...infinte number">Style... Infinate number appear</div>
</div>
请帮帮我
答案 0 :(得分:0)
尝试这样的事情: -
$(document).ready(function(){
$("div").each(function(){
if((this).attr('class') != undefined)
$(this).attr("id",$(this).attr("class"));
});
});
答案 1 :(得分:0)
抱歉JavaScript,我对jQuery并不擅长。详细信息在代码中注释。
注意:我提到容器的宽度与内容相同,不好意思。我把问题与另一个问题混淆了,但幸运的是,答案的其余部分仍然适用于你的问题。
$(function() {
var divs = document.querySelectorAll('#static div');
var divArray = Array.prototype.slice.call(divs);
var dyn = document.getElementById('dynamic');
for (var i = 0; i < divArray.length; i++) {
var klass = divArray[i].getAttribute('class');
var klone = divArray[i].cloneNode(true);
klone.setAttribute('id', klass);
dyn.appendChild(klone);
}
});
/* JavaScript Breakdown */
// 1. jQuery ready wrapper
// 2. Make a NodeList of all divs inside of section#static
// 3. Convert NodeList into an array
// 4. Reference section#dynamic
// 5. Iterate through divArray
// 6. Retrieve each of the divs' class
// 7. Clone each div
// 8. Each clone get's an id based on the class of the original element
// 9. Clone is appended to section#dynamic
body {
margin: 0;
padding: 0;
}
section {
background: rgba(0, 0, 0, .3);
outline: 3px dashed blue;
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
margin: 20px;
}
div {
outline: 2px solid red;
width: 100px;
}
p {
margin: 10px;
}
[id^="style"]:after {
content: ' ★';
font-size: 20px;
color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="static">
<div class="style1">Get External Content</div>
<div class="style2">Get External Content</div>
<div class="style3">Get External Content</div>
<div class="style4">Get External Content</div>
</section>
<p>The sections have the width of their contents.<sup>CSS 8,9,10</sup></p>
<p>The cloned divs below each has a gold star. This is proof that each clone has an id that starts with "style".<sup>CSS 17</sup> You can use the dev tools to view the clones' ids</p>
<p>
<section id="dynamic"></section>