почему getelementbyid не работает с динамически добавленным HTML в JavaScript без библиотек - PullRequest
0 голосов
/ 04 октября 2019

для моего школьного проекта я должен сделать веб-сайт одностраничным, но я не могу использовать библиотеки.

Я нашел этот код JavaScript для достижения этого main.js:

// Encapsulates an HTTP GET request using XMLHttpRequest.
// Fetches the file at the given path, then
// calls the callback with the text content of the file.
function fetchFile(path, callback){

    // Create a new AJAX request for fetching the partial HTML file.
    var request = new XMLHttpRequest();

    // Call the callback with the content loaded from the file.
    request.onload = function () {
        callback(request.responseText);
    };

    // Fetch the partial HTML file for the given fragment id.
    request.open("GET", path);
    request.send(null);
}

// Gets the appropriate content for the given fragment identifier.
function getContent(fragmentId, callback){
    fetchFile( fragmentId + ".html", callback );
}

// Sets the "active" class on the active navigation link.
function setActiveLink(fragmentId) {
    if (fragmentId != "login") {

    var navbarDiv = document.getElementById("navbar"),
        links = navbarDiv.children,
        i, link, pageName;
    for (i = 0; i < links.length; i++) {
        link = links[i];
        pageName = link.getAttribute("href").substr(1);
        if (pageName === fragmentId) {
            link.setAttribute("class", "active");
        } else {
            link.removeAttribute("class");
        }
    }
}
}

// Updates dynamic content based on the fragment identifier.
function navigate(){

    // Get a reference to the "content" div.
    var contentDiv = document.getElementById("content"),

        // Isolate the fragment identifier using substr.
        // This gets rid of the "#" character.
        fragmentId = location.hash.substr(1);

    // Set the "content" div innerHTML based on the fragment identifier.
    getContent(fragmentId, function (content) {
        contentDiv.innerHTML = content;
    });

    // Toggle the "active" class on the link currently navigated to.
    setActiveLink(fragmentId);
}

// If no fragment identifier is provided,
if(!location.hash) {

    // default to #home.
    location.hash = "#login";
}

// Navigate once to the initial fragment identifier.
navigate();

// Navigate whenever the fragment identifier value changes.
window.addEventListener("hashchange", navigate);

Мойhtml index, куда я загружаю динамическую html-страницу:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Navigation Example</title>

</head>
<body>

<!-- Dynamic content will be placed here by JavaScript. -->
<div id="content"></div>

<!-- The JavaScript code for dynamic behavior. -->
<script src="js/main.js"></script>
<script src="js/login.js"></script>


</body>
</html>

. Это динамически добавляемый html-файл с main.js:

<link rel="stylesheet" href="css/index.css">
<div id="wrapper">
    <div id="left">
        <div id="signin">
            <div class="logo">
                <img src="images/logo.png" alt="Logo" />
            </div>
            <form>
                <div>
                    <label>Gebruikersnaam</label>
                    <input type="text" class="text-input" />
                </div>
                <div>
                    <label>Wachtwoord</label>
                    <input type="password" class="text-input" />
                </div>
                <button id="button-login" type="button" class="primary-btn">Inloggen</button>
            </form>
            <div class="links">
                <a href="#">Wachtwoord vergeten</a>
                <a href="#">Login als quiz beheerder</a>
            </div>
            <div class="or">
                <hr class="bar" />
                <span>OF</span>
                <hr class="bar" />
            </div>
            <a href="#" class="secondary-btn">Maak een nieuw account aan</a>
        </div>
        <footer id="main-footer">
            <p>Copyright &copy; 2019, Thomas Ponzo Alle rechten voorbehouden</p>
            <div>
                <a href="#">Gebruiksvoorwaarden</a> | <a href="#">Privacybeleid</a>
            </div>
        </footer>
    </div>
    <div id="right">
        <div id="showcase">
            <div class="showcase-content">
                <h1 class="showcase-text">
                    Beoordeel de  <strong>Website!</strong>
                </h1>
                <a id="button-document" class="secondary-btn">Start het beoordelingsproces</a>
            </div>
        </div>
    </div>
</div>

login.js:

/**
 * Add actions to page buttons 
 */
function addButtonActions() {
    var loginButton = document.getElementById('button-login');
    var documentButton = document.getElementById('button-document');

    loginButton.addEventListener("click", function () {
        showStartPage();
    });
    documentButton.addEventListener("click", function () {
        showDocumentPage();
    });
}

/**
 * Show start page
 */
function showStartPage() {
    window.open("quizhome.html", "_self");
    console.log("test")
}

/**
 * Show questions page
 */
function showDocumentPage() {
window.open("documentation/index.html", '_blank');
}

// Updates dynamic content based on the fragment identifier.
function navigate(){

    // Get a reference to the "content" div.
    var contentDiv = document.getElementById("content"),

        // Isolate the fragment identifier using substr.
        // This gets rid of the "#" character.
        fragmentId = location.hash.substr(1);

    // Set the "content" div innerHTML based on the fragment identifier.
    getContent(fragmentId, function (content) {
        contentDiv.innerHTML = content;
    });

    // Toggle the "active" class on the link currently navigated to.
    setActiveLink(fragmentId);
};

// Sets the "active" class on the active navigation link.
function setActiveLink(fragmentId) {
    if (fragmentId == "login") {
        addButtonActions();
    }
};

// Navigate once to the initial fragment identifier.
navigate();

Моя проблема в том, что я не могу получить ссылку на мои кнопки в login.js. Мой вопрос: как мне это архивировать в javascript без использования библиотек?

...