gpt4 book ai didi

javascript - 根据按钮 ID 显示/隐藏表单

转载 作者:行者123 更新时间:2023-11-28 04:45:28 25 4
gpt4 key购买 nike

我正在尝试为每个表单构建一个按钮;当用户点击它时,具有特定id的特定表单将再次显示或隐藏。

我已经尝试过下面的 JavaScript 代码,但它不起作用。

这段代码是错误的还是我错过了什么?有人有其他想法吗?提前致谢。

$(function(){
$('.btn').on('click', function(e){
e.preventDefault();
$(this).next('.form2').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$result_posts = $conn -> prepare("SELECT * FROM posts WHERE post_topic=:post_topic ORDER BY DATE(post_date) ASC");
$result_posts -> bindParam(':post_topic',$topic_id);
$result_posts -> execute();
while ($row2 = $result_posts ->fetch(PDO::FETCH_ASSOC))
{
?>

<a class="btn" id="<?php echo $row2['post_id']; ?>"><i class="fa fa-commenting" aria-hidden="true"></i>Comment</a>

<form name="form2" class="form2" id=" <?php echo $row2['post_id']; ?>" style="display:none">
<textarea class="commenting" id="commenting" placeholder="Comment here..." cols="30" rows="5"></textarea>
<input type="submit" class="comment_submit2" value="Submit" >
</form>

<?php } ?>

最佳答案

需要使用toggle():-

工作示例:-

$(function(){
$(document).on('click', '.btn',function(e) {
e.preventDefault();
$(this).next('.form2').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn"><i class="fa fa-commenting" aria-hidden="true"></i>Comment</a>

<form name="form2" class="form2" style="display:none">
<textarea class="commenting" id="commenting" placeholder="Comment here..." cols="30" rows="5"></textarea>
<input type="submit" class="comment_submit2" value="Submit" >
</form>

<br>
<br>
<a class="btn"><i class="fa fa-commenting" aria-hidden="true"></i>Comment</a>

<form name="form2" class="form2" style="display:none">
<textarea class="commenting" id="commenting" placeholder="Comment here..." cols="30" rows="5"></textarea>
<input type="submit" class="comment_submit2" value="Submit" >
</form>

注意:- 请注意在任何情况下都不会重复任何 id(在您的代码中,按钮 id 及其相应的表单 id 会发生这种情况)。

我已经从我的代码中的按钮和表单中删除了 id。 (如果需要,请尝试使每一个都不同)

关于javascript - 根据按钮 ID 显示/隐藏表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com