<div class="form-group">
<div >
<a href="/addcourse">
<button class="btn btn-primary ">add course</button>
</a>
<div class="center">
<h1>manage courses</h1>
</div>
<div style="padding-left: 500px">
<form class="form-horizontal" style="width: 50%;">
<div class="form-group">
<label for="faculty" class="col-sm-2 control-label" ></label>
<div class="col-sm-10">
<div class="btn-group">
<button index=0 id='facultyDropdown' class="btn">Faculties</button>
<button class="btn dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
{{#facultyId}}
<li><a index="{{id}}">{{faculty}}</a></li>
{{/facultyId}}
</ul>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="bottom" value="submit" class="btn btn-primary submit">
<table class="table">
<thead>
<tr>
<th scope="col1" >corse code</th>
<th scope="col1" >course name</th>
<th scope="col2">credit hourse</th>
<th scope="col5"></th>
<th scope="col6"></th>
</tr >
<tbody id="myTable"></tbody>
</thead>
</table>
</div>
</div>
</form>
</div>
这个HTML页面有2个主按钮,我在每个表行中生成了另外两个按钮。行中的两个按钮不能使用 AJAX 。
$(document).ready(function(){
function buildTable(data){
document.getElementById('myTable').innerHTML = "";
var table = document.getElementById('myTable');
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].code}</td>
<td>${data[i].course}</td>
<td>${data[i].id}</td>
<td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" class="update" >update</button></td>
<td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" class="delete" >delete</button></td>
</tr>`
table.innerHTML += row
}
}
$(".dropdown-menu li a").click(function(){
const index = $(this).attr('index');
$("#facultyDropdown").attr('index', index);
$("#facultyDropdown").text($(this).text());
});
$("#submit").click(function() {
console.log('alaa');
const facultyId = $("#facultyDropdown").attr('index');
$.ajax({
type: "post",
url: `/api/v1/faculties/`+`${facultyId}`,
success:function(res){
courses= res
buildTable(courses)
console.log('courses')
}
});
});
$(".delete").click(function() {
const corseid = $(this).attr("id");
console.log(corseid);
$.ajax({
type: "delete",
url: `/api/v1/courses/`+`${corseid}`,
success:function(res){
alert(`course deleted ${res}`)
}
});
});
$(".update").click(function() {
const corseid = $(this).attr("id");
console.log(corseid);
$.ajax({
type: "put",
url: `/api/v1/courses/`+`${corseid}`,
success:function(res){
alert(`course deleted ${res}`)
}
});
});
});
这是上面的 AJAX 代码,我不明白下拉列表和添加课程按钮和提交按钮是工作只有更新和删除按钮不工作。
1条答案
按热度按时间5gfr0r5j1#
问题是,当您创建事件处理程序时,这些元素并不存在(因为它们只在单击
submit
后才存在)。您需要使用事件委托,有几种方法可以做到这一点,这可能是最简单的: