Javascript 如何查找div的id,并将这些名称作为类分配给其他div?
我对jquery相当陌生,无法理解这一点。我有3个不同id的div,但都以“sharedform”开头。我想循环遍历这些div,获取每个id,并将其作为标识类分配给每个div前面的“slideHead”div。任何帮助都将不胜感激 HMTL: 我建议:Javascript 如何查找div的id,并将这些名称作为类分配给其他div?,javascript,jquery,addclass,Javascript,Jquery,Addclass,我对jquery相当陌生,无法理解这一点。我有3个不同id的div,但都以“sharedform”开头。我想循环遍历这些div,获取每个id,并将其作为标识类分配给每个div前面的“slideHead”div。任何帮助都将不胜感激 HMTL: 我建议: // get all elements whose id starts with 'sharedform', iterate over that collection: $('div[id^=sharedform]').each(function
// get all elements whose id starts with 'sharedform', iterate over that collection:
$('div[id^=sharedform]').each(function (){
// find the parent of the 'this' element:
$(this).parent()
// find the previous element, if it matches the passed-in selector:
.prev('.slideHead')
// add the id of the element we initially selected as a class:
.addClass(this.id);
});
$('div[id^=sharedform]')。每个(函数(){
$(this.parent().prev('.slideHead').addClass(this.id);
});代码>
div{
宽度:80%;
保证金:0自动;
最小高度:2米;
填充:0.5em;
边框:1px实心#000;
}
.滑头{
背景色:#f00;
}
.slideHead.sharedform\.什么{
背景色:#0f0;
}
div中的一些文本
这应该可以做到:
$('[id^=sharedform]').each(function() {
$(this).closest('.drawer').prev().addClass( this.id );
});
$('[id^=sharedform]')。每个(函数(){
$(this).closest('.drawer').prev().addClass(this.id);
});
var newHTML=$('body').html(),
out=$('',{class:'out'}).appendTo('body');
text('newHTML\n'+newHTML)代码>
.slidehead
是具有slidehead
类的所有元素的选择器。您希望找到每个类,并为每个类将类添加到DOM上最近的同级。所以你想要一个每个,这就是我想的,只是不确定在哪里。对。不幸的是,这些类名与无法访问的更深层次的编程联系在一起。
// get all elements whose id starts with 'sharedform', iterate over that collection:
$('div[id^=sharedform]').each(function (){
// find the parent of the 'this' element:
$(this).parent()
// find the previous element, if it matches the passed-in selector:
.prev('.slideHead')
// add the id of the element we initially selected as a class:
.addClass(this.id);
});
$('[id^=sharedform]').each(function() {
$(this).closest('.drawer').prev().addClass( this.id );
});