简体   繁体   中英

JavaScript won't show/hide div - working with PHP/MySQL

In my PHP/MySQL while loop when selecting data for an activity feed, I'm trying to show comments underneath each post so that when you click "show", it shows all of the comments.

I'm using the following code in the while loop (so this is dynamically displayed numerous times for each separate update):

<script language="javascript"> 
function toggle' . $act_item_id . '() {
    var ele = document.getElementById("toggleText' . $act_item_id . '");
    var text = document.getElementById("displayText' . $act_item_id . '");
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
} 
</script>

<a id="displayText' . $act_item_id . '" href="javascript:toggle' . $act_item_id . '();">show</a>
<div id="toggleText' . $act_item_id . '" style="display: none">' . $responseList . '</div>

' . $act_item_id . ' contains the ID of the update, making everything unique.

When you click show, the JavaScript doesn't show the div.

FYI: Content is loaded into another page via an AJAX call.

AJAX call is as follows:

function list_activity(){
    var hr = new XMLHttpRequest();
    hr.onreadystatechange = function(){
    if (hr.readyState==4 && hr.status==200){
    document.getElementById("viewActivity").innerHTML = hr.responseText;
    }
    }
    hr.open("GET", "listActivity.php?t=" + Math.random(), true);
    hr.send();
}

I'm not entirely sure you can create and call JS functions like that. Besides, I don't see any reason to re-create the function for each section. Why don't you simply parameterize you function and change the parameter each time through?

Define function once

<script>
function toggle(act_item_id) {
    var ele = document.getElementById("toggleText' . act_item_id . '");
    var text = document.getElementById("displayText' . act_item_id . '");
    if(ele.style.display == "block") {
        ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
} 
</script>

Then you can loop through

while (some condition) {
    ...
    <a id="displayText' . $act_item_id . '" href="javascript:toggle('.$act_item_id.');">show</a>
    <div id="toggleText' . $act_item_id . '" style="display: none">' . $responseList . '</div>
    ...
}

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