Я хочу щелкнуть элемент, чтобы переключить класс, на который ссылается полностью несвязанный элемент (а не дочерний, родительский или родственный): Например:
HTML:
<div class="parent">
<button class="btn">
this is button!!!
</button>
<div class="allo">
test
</div>
</div>
<div class="parent">
<button class="btn">
this is button!!!
</button>
<div class="allo">
test
</div>
</div>
CSS:
.allo {
display: none;
}
.btn {
padding: 10px;
}
JavaScript: (или что-то вроде этого)
var el = document.getElementByClassName("allo");
function toggle(){
for (i=0; i<btn.length; i++) {
if (el[i].style.display === 'none'){
el[i].style.display = 'block';
} else {
el[i].style.display = 'none'
}
}
}
При нажатии кнопки в родительском div откройте блок текста, принадлежащий этому родительскому элементу.
Хорошо давайте использовать document.querySelectorAll
для этого и обновим ваш скрипт с помощью более современной JS.
var btn = document.querySelectorAll(".btn"); //we can select them on the same manner as css selectors.
var el = document.querySelectorAll(".allo");
//borrow array forEach to iterate over the node list
//use call to pass the node list (btn) as this
Array.prototype.forEach.call(btn, function(element, index){
//use bind to pass index to the function
element.addEventListener("click", toggleViewFunc.bind(element, index), false);
//use addEventListener to attach click handlers
});
function toggleViewFunc(index)
{
//because the button is in the same parent as the div "allo" the indices match.
//if this is not the case you could use this.nextSibling instead of el[index] because "allo" is the sibling of button.
//use classlist and toggle to turn show or off.
el[index].classList.toggle("show");
}
.allo {
display: none;
}
.btn {
padding: 10px;
}
/*introduce extra show class */
.show{
display: block !important;
}
<div class="parent">
<button class="btn">
this is button!!!
</button>
<div class="allo">
test
</div>
</div>
<div class="parent">
<button class="btn">
this is button!!!
</button>
<div class="allo">
test
</div>
</div>
Это результат, который вы ищете? Кнопка переходит к функции переключения, затем мы идем в HTML, просматриваем все элементы HTML этого элемента, ища элемент с классом "allo", и после того, как мы найдем этот элемент, мы изменим его отображение. Другой элемент остается невредимым.
JAVASCRIPT:
var btn = document.getElementsByClassName("btn");
Array.prototype.forEach.call(btn, function (current) {
current.addEventListener('click', toggle(current), false);
})
function toggle(el){
var divParent = el.parentElement;
var divsInsideParent = divParent.children;
var divAllo = null;
for (int i = 0; i < divsInsideParent.length; i = i + 1){
if (divsInsideParent[i].classList.contains("allo")){
divAllo = divsInsideParent[i];
}
}
if (divAllo.style.display === 'none') {
divAllo.style.display = 'block';
} else {
divAllo.style.display = 'none'
}
}
i
перед тем, как использовать его в цикле for.getElementsByClassName
, а не getElementByClassName
Вам понадобится кнопка EventListener для вас. Я обновил ваш скрипт: https://jsfiddle.net/6oz0tsgp/
/* change "Element" to "Elements" */
var el = document.getElementsByClassName("allo");
var btn = document.getElementsByClassName("btn");
/* declare i */
var i = 0;
/**
* call Array.prototype because the HTMLCollection
* returned by getElementsByClassName does not have
* a forEach-Property
*/
Array.prototype.forEach.call(btn, function (current) {
current.addEventListener('click', toggle, false);
})
function toggle(){
for (i=0; i<btn.length; i++) {
if (el[i].style.display === 'none') {
el[i].style.display = 'block';
} else {
el[i].style.display = 'none'
}
}
}