Я хочу нажать на элемент, чтобы переключить класс, на который ссылается совершенно не связанный элемент

1

Я хочу щелкнуть элемент, чтобы переключить класс, на который ссылается полностью несвязанный элемент (а не дочерний, родительский или родственный): Например:

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 откройте блок текста, принадлежащий этому родительскому элементу.

https://jsfiddle.net/5sw4btga/

  • 2
    не стихия, а стихия
  • 0
    спасибо это опечатка :)
Показать ещё 2 комментария
Теги:

3 ответа

0
Лучший ответ

Хорошо давайте использовать 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>
  • 1
    СПАСИБО ОЧЕНЬ ОЧЕНЬ ОЧЕНЬ! Я провел много часов с этой проблемой! Ты сделал мой день!! вау :) я счастлив! :)
0

Это результат, который вы ищете? Кнопка переходит к функции переключения, затем мы идем в 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'
    }
}
  • 0
    Большое спасибо! Для вашего решения! !)
0
  • Выпуск 1: вы не объявили i перед тем, как использовать его в цикле for.
  • Проблема 2: у вас есть опечатка, она 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'
        }
    }
} 
  • 1
    БОЛЬШОЕ СПАСИБО !! Будь счастлив!! ) и для лучшей кармы !! ++++

Ещё вопросы

Сообщество Overcoder
Наверх
Меню