рефакторинг javascript код для создания цикла - PullRequest
2 голосов
/ 04 апреля 2020

Я практикую Javascript. Я хочу, чтобы каждая ссылка отображала что-то другое в DOM при нажатии.

Вот мой текущий Javascript, который работает.

//used a 'for' loop to hide each 'notes' page
const element = document.querySelectorAll(".notes");
for (let x = 0; x < element.length; x++)
  element[x].style.display = 'none';

const html_link= document.getElementById('html-link');
const css_link = document.getElementById('css-link');
const javascript_link = document.getElementById('js-link');

const html_notes = document.getElementById('html-notes');
const css_notes = document.getElementById('css-notes');
const js_notes = document.getElementById('js-notes');

html_link.onclick = function() {
    html_notes.style.display = "block";
    css_notes.style.display = "none";
    js_notes.style.display = "none";
}

css_link.onclick = function() {
    css_notes.style.display = "block";
    html_notes.style.display = "none";
    js_notes.style.display = "none";
}

javascript_link.onclick = () => {
    js_notes.style.display = "block";
    html_notes.style.display = "none";
    css_notes.style.display = "none";
}

Как я могу сделать рефакторинг, используя для l oop? Я думал для каждой нажатой ссылки, отображать заметки. Но я изо всех сил пытаюсь понять, как правильно отображать div с примечаниями, которые соответствуют нажатой ссылке. Это то, что я начал.

const links = document.querySelectorAll('.links')

for (const link of links) {
  link.addEventListener('click', function() {

    let ref = event.target.parentElement.id.replace('link','notes'); 
//replaces parent element with id 'notes'
    const show = document.getElementById(ref);
//'show' div with new id

  })
}

1 Ответ

0 голосов
/ 04 апреля 2020

Добро пожаловать, приятель, новичок ie! Я позволил себе написать html и очень минимальный стиль. Это моя первая попытка ответа на stackoverflow.

Обратите внимание на некоторые особенности кода, который я добавил:

  • добавлен класс 'links' для всех ссылок.
  • класс 'notes' добавлен ко всем заметкам.
  • Атрибут 'data-notes' добавлен ко всем ссылкам (с идентификатором соответствующих ссылок каждой ссылки)
<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
</head>

<body>

    <div class="outer">
        <div id="html-link" data-notes="html-notes" class="links">
            <p>html-link</p>
        </div>
        <div id="css-link" data-notes="css-notes" class="links">
            <p>css-link</p>
        </div>
        <div id="javascript-link" data-notes="javascript-notes" class="links">
            <p>javascript-link</p>
        </div>
    </div>

    <div class="outer">
        <div id="html-notes" class="notes">
            <p>html-notes</p>
        </div>
        <div id="css-notes" class="notes">
            <p>css-notes</p>
        </div>
        <div id="javascript-notes" class="notes">
            <p>javascript-notes</p>
        </div>
    </div>

    <style>
        .links {
            cursor: pointer;
            background: green;
            color: white;
            padding: 1rem;
            margin: 1rem;
        }

        .notes {
            display: none;
            background: blue;
            color: white;
            padding: 1rem;
            margin: 1rem;
        }

        .outer {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-around;
            margin: 2rem 0;
        }

    </style>

    <script>
            const links = document.querySelectorAll('.links');
            const notes = document.querySelectorAll('.notes');

            for (const link of links) {
                link.onclick = function () {
                    for (const note of notes) {
                        if (note.id == link.dataset.notes) {
                            note.style.display = "block";
                        } else {
                            note.style.display = "none";
                        }
                    }
                }
            }

    </script>

</body>
</html>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...