我正在Wordpress上的這個項目上工作,我需要使用append和刪除動態更改HTML中的形式。我嘗試過使用它,但有一些錯誤。它不按照它應該的方式工作。這是代碼的簡要說明:如何使用append和remove來更改html表單?
<?php
/* Template Name: FirstStarRatingSystem */
?>
<div class="t1">
<button class="add_form_field">Add New Field <span style="font-
size:16px; font-weight:bold;">+ </span></button><br>
<input type="text" class="t1" name="fname1" id="text1" placeholder="First
Rating"></div>
<div class="rating1">
<legend>Please rate:</legend>
<input type="radio" class="rating1" id="star5" name="rating1" value="5" />
<label for="star5" title="Rocks!">5 stars</label>
<input type="radio" class="rating1" id="star4" name="rating1" value="4" />
<label for="star4" title="Pretty good">4 stars</label>
<input type="radio" class="rating1" id="star3" name="rating1" value="3" />
<label for="star3" title="Meh">3 stars</label>
<input type="radio" class="rating1" id="star2" name="rating1" value="2" />
<label for="star2" title="Kinda bad">2 stars</label>
<input type="radio" class="rating1" id="star1" name="rating1" value="1" />
<label for="star1" title="Sucks big time">1 star</label>
</div>
<br><br>
<br><br>
<br><br>
<div class="t2"></div>
<div class="rating2"></div>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(document).ready(function() {
var max_fields=2;
var t2=$(".t2");
var rating2=$(".rating2");
var add_button=$(".add_form_field");
var x=1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
if(x==2)
$(t2).append('<div class="t2"><input type="text" class="t2" name="fname2"
id="text2" placeholder="Second Rating"></div>'); //add input box
$(rating2).append('<div class="rating2"><legend>Please rate1:</legend>
<input type="radio" class="rating2" id="1star5" name="rating2" value="5" />
<label for="1star5" title="Rocks!">5 stars</label> <input type="radio"
class="rating2" id="1star4" name="rating2" value="4" /> <label for="1star4"
title="Pretty good">4 stars</label> <input type="radio" class="rating2"
id="1star3" name="rating2" value="3" /> <label for="1star3" title="Meh">3
stars</label> <input type="radio" class="rating2" id="1star2" name="rating2"
value="2" /> <label for="1star2" title="Kinda bad">2 stars</label> <input
type="radio" class="rating2" id="1star1" name="rating2" value="1" /> <label
for="1star1" title="Sucks big time">1 star</label><a href="#"
class="delete">Delete</a></div>'); //add 5 star rating.
}
else
{
alert('You Reached the limits')
}
});
$(rating2).on("click",".delete", function(e){
e.preventDefault();
$(t2).remove();
$(this).parent('div').remove();
x--;
})
});
</script>
<style>NECESSARY CSS</style>
正如你會想通了,這個代碼是一個5星級評級系統一起顯示一個動態輸入表單。用戶可以選擇輸入表格數量和5星級評分。目前,出於測試目的,該數目僅限於2次(var max_fields = 2;)。我需要同時添加輸入表單和5星評級,同時用戶按下添加按鈕,同時當用戶按下刪除按鈕時同時刪除輸入表單和5星評級,但目前這不能正常工作,並導致第二次添加輸入表格被永久刪除,只有5星評級正常工作,即。正確添加和刪除。
預先感謝。
第一張圖片顯示的第一輸出增加2輸入表格和5星級評分之前:
第二個圖像顯示按下「添加新字段+」的第2輸入表格後刪除按鈕後和5星級評分:
謝謝,它的工作現在。 – codewiz
@codewiz welcome :) – Roljhon
如果可能,您是否可以提供任何資源以瞭解有關此主題的更多信息?謝謝。 – codewiz