【问题标题】:How to put many show/hide functions on single page? [duplicate]如何在单个页面上放置许多显示/隐藏功能? [复制]
【发布时间】:2020-01-04 01:39:22
【问题描述】:

从数据库中获取信息

$video_id = $_GET['id'];
$query = "SELECT * FROM video_comments WHERE video_id = :video_id";
$stmt = $pdo->prepare($query);
$stmt->bindValue(':video_id',$video_id);
$stmt->execute();

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

$id = $row['id']; // The id for each comment

// Show/Hide Script
echo '<script>function replyToCommentFunction'.$id.'() {
var x = document.getElementById("replyToComment'.$id.'");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}</script>';

<button name="replyToComment" class="videoCommentsReplyButton" onClick="replyToCommentFunction'.$id.'()">Reply</button>

// The Div to show...
echo '<div id="replyToComment'.$id291.'">';
echo 'Hello, World!';
echo '</div>';

}

我以为我有这个工作。但是现在,只有一个“回复”按钮在页面上起作用。最近的回复按钮刷新了页面,这让我感到困惑,因为不存在脚本或操作,这会告诉它提交表单或刷新页面。我将不胜感激任何帮助。谢谢。

【问题讨论】:

    标签: javascript php show-hide


    【解决方案1】:

    当你可以创建一个并让所有按钮都使用它时,你为什么要创建很多函数?

    在页面末尾添加此代码:

    <script type="text/javascript">
    function replyToCommentFunction(x) {
        if(x.style.display === "block") {
            x.style.display = "none";
        } else {
            x.style.display = "block";
        }
    }
    </script>
    

    将按钮编辑为:

    <button name="replyToComment" class="videoCommentsReplyButton" onClick="replyToCommentFunction(this);">Reply</button>
    

    【讨论】:

    • 如果页面上所有的DIV都具有相同的id值,函数如何理解扩展哪个DIV,实际上甚至是不允许的。
    • 是的,(this) 会将被点击的元素发送给函数。该函数不会通过 id 捕获元素,这就是我删除这一行的原因。您函数上的 x 已经是元素,因此不再需要“getElementById”。 ;)
    • 好的,但还是有点困惑,我从你那里得到了这个。 one functiondiv adiv bdiv cbutton abutton bbutton c。信息从按钮 a 传递到唯一的功能。那么从函数到,哪个div呢?究竟是什么告诉按钮哪个 div 应该展开,因为 id 不再需要了。必须有一些东西来识别正在扩展的 div,对吧?
    • 您可以在按钮的 onclick 属性上执行此操作。 &lt;button onclick='replyToCommentFunction(" . $id . ");'&gt;&lt;/button&gt;,那么您可以通过 ID 获取函数中带有变量 x 的 div 元素。 document.getElementById("replyToComment" + x).
    • 啊,我明白了。非常感谢。我一直认为while循环脚本是不合适的。直到现在我才知道另一种方法。谢谢。
    【解决方案2】:

    您可以尝试将 type="button" 添加到刷新页面的按钮吗?

    【讨论】:

    • 这是一个很好的做法,不管它是否解决了操作的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2018-08-12
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多