繁体   English   中英

如何默认隐藏表单并单击显示

[英]How to hide form by default and show on click

我有一个评论表格,它由php while循环显示

Post 1
Comment box 1

Post 2
Comment box 2

我想默认隐藏评论框,当用户单击评论链接时,应显示该表单

这是我尝试过的

$(document).ready(function() {

    $("#showActionComment").hide();
    $("#showActionComment").click(function() {
        $("#comForm").show();
    });
});

HTML

php while loop starts here
Post 1
<a href="javascript:void(0);" id="comForm">Comment</a>
<form action="/comment.php" class="form-horizontal" id="showActionComment">
<input type="text" name="comment">
</form>

php while loop ends here

由于循环,上面的代码可能有15个在我的情况下不起作用

您将在具有相同ID的循环中创建元素。 HTML中的标识符必须是唯一的,否则它将是无效的HTML。 您可以使用类选择器和那里的关系来遍历元素

CSS .showActionComment {display:none;}

PHP脚本生成HTML

php while loop starts here

    <a href="javascript:void(0);" class="comForm">Comment</a>
    <form action="/comment.php" class="form-horizontal showActionComment">
        <input type="text" name="comment">
    </form>

php while loop ends here

jQuery脚本 ,您需要在comForm元素而非form上订阅click事件。 在此代码段中,我使用了.next()

获取匹配的元素集中每个元素的紧随其后的同级。

$(document).on('click',".comForm", function(event) {
    event.preventDefault();
    $(this).next(".showActionComment").show();
});

注意:动态生成元素时,请使用.on()委托事件方法使用事件委托。

一般语法

$(document).on('event','selector',callback_function)

设置类的display:none属性。

.form-horizontal{
     display:none
}

每当您刷新页面时,它都不会显示该表单。
在点击事件中,它将根据您的点击事件将display:none更改为display:block

默认情况下通过CSS隐藏表单

#comForm {
display:none;
}

然后单击该按钮,将其显示

 $("#showActionComment").click(function() {
        $("#comForm").show();
    });

也许您的意思是-注释ID必须是唯一的:

 $(function() { $(".showForm").on("click",function(e) { e.preventDefault(); $(this).next(".showActionComment").toggle(); }); }); 
 .showActionComment { display:none } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="enableJavaScript.html" class="showForm">Comment</a> <form action="/comment.php" class="form-horizontal showActionComment"> <input type="text" name="comment"> </form><br/> <a href="enableJavaScript.html" class="showForm">Comment</a> <form action="/comment.php" class="form-horizontal showActionComment"> <input type="text" name="comment"> </form> 

如果您使用AJAX加载评论和链接,请更改

  $(".showForm").on("click",function(e) {

  $(document).on("click",".showForm",function(e) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM