简体   繁体   中英

Javascript Client Side Include not injecting on Onclick Event

I am working on javascript client include and I'm using this code:

window.onload = function() {
    var elements = document.getElementsByTagName('*'),
        i;
    for (i in elements) {
        if (elements[i].hasAttribute && elements[i].hasAttribute('data-include')) {
            fragment(elements[i], elements[i].getAttribute('data-include'));
        }
    }
    function fragment(el, url) {
        var localTest = /^(?:file):/,
            xmlhttp = new XMLHttpRequest(),
            status = 0;

        xmlhttp.onreadystatechange = function() {
            /* if we are on a local protocol, and we have response text, we'll assume
 *                  things were sucessful */
            if (xmlhttp.readyState == 4) {
                status = xmlhttp.status;
            }
            if (localTest.test(location.href) && xmlhttp.responseText) {
                status = 200;
            }
            if (xmlhttp.readyState == 4 && status == 200) {
                el.outerHTML = xmlhttp.responseText;
            }
        }

        try { 
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        } catch(err) {
            /* todo catch error */
        }
    }
}

This above code works really well when the page loads to include external .html files, using the following syntax:

<div id="myid" data-include="templates/myExternalTemplate.html"></div>

The above template will be loaded into the page.

My problem comes when I try to change the template from one to the other using an onclick event:

<div onclick="changeTemplate();"></div>

I have tried:

function changeTemplate() {
document.getElementById("myid").setAttribute("data-include","templates/2.html");
}

The above function is returning the following error:

*TypeError: document.getElementById(...) is null*

How can I make this work?

First, you need to give your div an id.

<div id="myId" data-include="templates/myExternalTemplate.html"></div>

Also, your function keyword should not be capitalized:

function changeTemplate() {
    document.getElementById("myId").setAttribute("data-include","templates/2.html");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM