使用追加时,我添加的元素会多次添加到我的页面。从我理解的附加添加到所有附加元素,这就是它多次附加的原因。我尝试使用克隆,但没有成功。解决方法是什么? 这是我的代码
脚本
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#Test').click(function(){ //this is the method that call append
$('#Get_Id').submit(function(event){
event.preventDefault();
var $form = $( this );
url = $form.attr( "action" );
$.get( url, function(data){
console.log(data);
user_data = data;
var html = `<div class="note">
<p>${data[0].note}</p>
<form action="/delete/${data[0].id}" method="post" id="delete_note">
<input type="submit" name="submit" value="Delete" class='delete'/>
</form>
<form action="/AddDescription/${data[0].id}" method="post" class="update_note">
<label asp-for="Description" >Description</label>
<textarea name="Description" id="" cols="30" rows="10" class="Description">${data[0].description}</textarea>
<input type="submit" name="submit" class="update" value="Update"/>
</form>
</div>`
$('.added_notes').append(html);
});
});
});
});
});
</script>
HTML
@model ajaxNotes.Models.Home
<div class = "notes">
@{
if(ViewBag.Notes != null)
{
foreach(var note in ViewBag.Notes )
{
<div class = "note">
<p>@note.Note</p>
<form action="/delete/@note.Id" method="post" id="delete_note">
<input type="submit" name="submit" value="Delete" class='delete'/>
</form>
<form action="/AddDescription/@note.Id" method="post" class="update_note">
<label asp-for="Description" ></label>
<textarea name="Description" id="" cols="30" rows="10" class="Description">@note.Description</textarea>
<input type="submit" name="submit" class="update" value="Update"/>
</form>
</div>
}
}
}
</div>
<div class="added_notes">
</div>
<form asp-controller="Home" asp-action="AddNote" method="post" id="New_Note">
<label asp-for="Note" ></label>
<p><input asp-for="Note" class = "Note" name="Note"/> </p>
@{
if(ViewData["error"] != null)
{
<p>Please enter data for Notes</p>
}
}
<button type="submit">Add Note</button>
</form>
<form asp-controller="Home" asp-action="GetLastEntry" method="post" id="Get_Id">
<label asp-for="Note" ></label>
<p><input asp-for="Note" class = "Note" name="Note"/> </p>
@{
if(ViewData["error"] != null)
{
<p>Please enter data for Notes</p>
}
}
<button type="submit" id = "Test">Add Note</button>
</form>
答案 0 :(得分:1)
您在这里使用“点击”和“提交”是多余的。该按钮充当提交触发器,因此请选择一个。执行
时会产生问题POST
您正在为“提交”创建重复绑定,并且每次点击都会相乘。因此重复追加。
答案 1 :(得分:0)
调用集合中的last()jquery函数并依赖于该元素应该有效。
bar