动态地使div在href单击时展开

时间:2016-02-23 18:25:25

标签: javascript jquery html

我正在尝试根据锚链接点击动态扩展div。锚链接view comments将根据链接上的点击展开并显示用户评论。

我有一个包含以下两个相关表的数据库:

user_thoughts
  id
  message
  added_by

和......

user_comments
  id
  body_of_msg
  comment_posted_by
  comment_posted_to
  post_id

我有以下疑问:

$get_thoughts_from_db = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' ORDER BY id DESC LIMIT 10");
while ($row = mysqli_fetch_assoc($get_thoughts_from_db)) {
    $thought_id      = $row['id'];
    $message_content = $row['message'];
    $thoughts_by     = $row['added_by'];

和另一个从user_comments表中获取数据......

// Get the comments attahed to a users post...
$get_comm = mysqli_query ($connect, "SELECT * FROM user_comments WHERE post_id='$thought_id' ORDER BY post_id DESC");
$comment = mysqli_fetch_assoc ($get_comm);
    $comment_body           = $comment['body_of_msg'];
    $comment_posted_to      = $comment['comment_posted_to'];
    $comment_posted_by      = $comment['comment_posted_by'];
    $removed                = $comment['comment_removed'];

用户的每个想法都是回声,但当我按view comments时,它不会在div中加载评论。

以下是我的尝试:

<script language="javascript">
    function toggle <?php echo $thought_id ?>() {
        var ele = document.getElementById("toggleComment <?php echo $thought_id ?>");
        var text = document.getElementById("displayComment <?php echo $thought_id ?>");
        if (ele.style.display == "block") {
            ele.style.display = "none";
            } else {
                ele.style.display = "block";
                }
        }
</script>

这里是评论和链接的地方......

<div class='mini_nav' style='float: right;'>
                                <span class='glyphicon glyphicon-heart-empty' data-clicked='false' aria-hidden='true'></span> 
                                <span style='padding-left: 5px; padding-right: 5px;'> | </span>
                                <a href='#' onClick='javascript:toggle$thought_id()'> View comments </a> 
                            <div id='toggleComment$thought_id' style='display:none;'>
                                <br/> $message_content
                            </div>

我完全希望我的javascript能够正常工作,但它并没有用与think_id相同的post_id加载评论。

1 个答案:

答案 0 :(得分:0)

您可以像这样创建JS函数:

<script language="javascript">
    function toggle(id) {
        var ele = document.getElementById("toggleComment" + id);
        if (ele.style.display == "block") {
            ele.style.display = "none";
        } else {
            ele.style.display = "block";
        }
    }
</script>

定义你的html:

<div class='mini_nav' style='float: right;'>
    <span class='glyphicon glyphicon-heart-empty' data-clicked='false' aria-hidden='true'></span>
    <span style='padding-left: 5px; padding-right: 5px;'> | </span>
    <a href='#' onclick='toggle($thought_id)'> View comments </a>
    <div id='toggleComment$thought_id' style='display:none;'>
        <br/> $message_content
    </div>
</div>