问题:我对前端开发完全陌生。我已经使用 JSONP 和 AJAX 成功制作了一个表格,其中包含有关大学类(class)的一些数据。但是,我需要在每行的开头添加一个新列,默认为 + 号。单击此按钮后,将打开一组描述类(class)中所有学生的新数据,并且 + 变为 - 。我还看不出最好的方法来做到这一点。有什么建议吗?
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns=" http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script src="json-jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'http://xx.xxx.xxx.xx/getCourses.php',
dataType: 'jsonp',
jsonpCallback: "courses",
success: function( data ) {
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.courses.length; i++) {
drawRow(data.courses[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#dataTable").append(row);
row.append($("<td>" + rowData.courseName + "</td>"));
row.append($("<td>" + rowData.start + "</td>"));
row.append($("<td>" + rowData.end + "</td>"));
row.append($("<td>" + rowData.lecturerName + "</td>"));
}
</script>
</head>
<body>
<table id="dataTable">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</table>
</body>
</html>
最佳答案
您可以选择更改按钮的内容,或者简单地切换按钮上的类并让 css 更改视觉显示。 将公共(public)类应用于元素以简化事件绑定(bind)选择器。
我将添加一个数据属性,其中包含下一次请求学生数据所需的类(class)标识符。
function drawRow(rowData) {
var button='<anyElement data-courseId="'+ rowData.id +'" class="data-button">+</anyElement>';
var row = $("<tr />")
row.append('<td>'+button+'</td>');/* no need to wrap html in "$()" */
/* append other cells*/
/* do append to DOM after row created , makes for less DOM insertions*/
$("#dataTable").append(row);
}
然后在准备好的处理程序中为按钮添加一个事件处理程序。在事件处理程序中,this
引用当前实例。
$("#dataTable").on('click', '.data-button',function(){
/* text change method */
$(this).text(function( _ , currText){
return currText === '+' ? '-' : '+';
});
/* class change */
$(this).toggleClass('active');
/* get data */
var id= $(this).data('courseId');
/* make api call based on id*/
})
关于javascript - 向表格添加 + 号,显示更多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981069/