HTML可折叠性不会通过PHP加载持续存在

HTML可折叠性不会通过PHP加载持续存在

问题描述:

Basically, I'm creating a website where I'm using jQuery Collapse to format some elements. These elements, however, are being generated by a PHP script and loaded through Javascript (see below). For some reason, the loaded elements don't have the desired collapsibility.

I've confirmed that just placing the generated elements in as static HTML fixes the problem, but I would like for the HTML code to be generated at run-time.

Why is this? Is there anything I can do to fix it?

Thanks! Below is a code example of what I'm trying to do

index.html

...
<body onload="test()">
    <div id="content"> </div>
</body>
...

javascript

function test(){
    // Create the request object
    var httpReq = (window.XMLHttpRequest) ? new XMLHttpRequest()
        : new ActiveXObject("Microsoft.XMLHTTP");

    // When it loads,
    httpReq.onload = function() {
        // Convert the result back into JSON
        var result = httpReq.responseText;
        document.getElementById("content").innerHTML = result;
    };

    // Request the page
    try {
        httpReq.open("GET", "parser.php?", true);
        httpReq.send(null);
    } catch (e) {
        console.log(e);
    }
}

parser.php

echo '<div data-collapse="accordion"><h1>Test title</h1><div>Collapsed content</div></div>';

You will have to call jQuery Collapse after loading the content:

httpReq.onload = function() {
    // Convert the result back into JSON
    var result = httpReq.responseText;
    document.getElementById("content").innerHTML = result;
    $("#content").collapse();
};

The script is probably looking at the page at load-time so elements added after will not be affected by the script.

You will likely have to re-run the script after loading new content (which may or may not work), or find a better script that uses real-time DOM event handlers.