[英]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.