除了javascript我别无选择。我相信很多人都经历过这个。
HTML代码
length(g[g>150])
JS代码
<ul class="recordingslist"></ul>
..
..
..
<div class='test' style="display : none">
<ul class="recordingslist test1" ></ul>
</div>
..
..
..
<div class="testasdasdsad" style="display : none">
<ul class="recordingslist test2"></ul>
</div>
我有很多同一类的ul。
现在只有第一个ul可见,我想将“test”附加到那个可见的ul。
我们如何才能实现这一目标?
非常感谢你。
答案 0 :(得分:2)
根据您在评论中的说明,您正在搜索其父<ul>
元素具有<div>
属性的第一个display
元素,该元素不等于none
鉴于此,我建议:
// here we use Array.from() to convert the supplied Array-like
// NodeList into an Array, in order to use Array methods:
Array.from(
// here we find all <ul> elements with a class of
// 'recordingslist':
document.querySelectorAll('ul.recordingslist')
// we filter the resulting Array of <ul> elements, using
// Array.prototype.filter():
).filter(
// using an Arrow function, in which the 'ul' variable
// is a reference to the current <ul> element of the Array
// of <ul> elements over which we're iterating:
ul => window.getComputedStyle(
// we find the computed CSS properties of the node:
ul.parentNode, null
// and access its 'display' property to ensure that
// it's computed display property-value is not equal
// to the value of 'none' (so it should not be hidden):
).display !== 'none'
// we iterate over those elements retained in the Array,
// using Array.prototype.forEach
).forEach(
// here we use another Arrow function:
// ul: the current <ul> in the Array of <ul> elements,
// index: the index of the current <ul> in the Array
// of <ul> elements.
// here if the index is exactly equal to 0, we add the
// 'test' class-name, otherwise we add an empty string:
(ul, index) => ul.classList.add( index === 0 ? 'test' : '' )
);
参考文献:
答案 1 :(得分:0)
使用jquery让这变得轻而易举。建议在ul div中添加一个额外的属性,以标记div是否可见。像下面的东西
HTML
<ul visible=false class="recordingslist"></ul>
<ul visible=false class="recordingslist test1"></ul>
<ul visible=true class="recordingslist test2"></ul>
JS
let allElems = document.querySelectorAll('.recordingslist')
allElems.forEach((obj)=>{
if(obj.getAttribute('visible')==='true'){
obj.append('Hello there')
}
})
答案 2 :(得分:0)
例如,如果要仅选择ul可见对象,则使用jquery选择器:visible
:
$('ul:visible')。append('test');
或使用课程
$('。recordingslist:visible')。append('test');