我正在構建日誌以存儲我的運行時間,日期和距離。我目前有這是一個具有3列數據的表格和一個按鈕,用於將存儲在數據字段中的信息附加到表格的下一行。使用表格中的按鈕刪除特定行
<!DOCTYPE HTML>
<head>
<title>Running Diary</title>
<link type = "text/css" rel = "stylesheet" href= "running.css"/>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src ="running.js"></script>
</head>
<body>
<!-- Title at the top of page !-->
<h1 id = "title"> Running Diary </h1>
</br>
</br>
</br>
<!-- Table containing text/date fields and the entries for a running diary. !-->
<table id = "diary">
<!-- Column titles for the running diary !-->
<thead id = "diaryHeader">
<th>Date</th>
<th>Distance Ran (KM)</th>
<th>Time</th>
</th>
</thead>
<!-- The table row that contains the text field and enter button for adding each entry to the diary !-->
<tbody>
<tr id = "diaryFields">
<td> <input type="date" id="dateField"/></td>
<td> <input type="number" id="distanceField" placeholder="Distance"/> </td>
<td> <input type="text" id="timeField" placeholder="HH:MM:SS"/> </td>
<td> <input type="submit" value="Add" id="diarySubmit"/>
</tr>
</table>
</body>
和JS:
$(document).ready(function(){
//This handles the click function for diarySubmit button
$("#diarySubmit").on('click', function(){
//Taking values from each textbox
var distanceRan = $('#distanceField').val();
var timeRan = $('#timeField').val();
var dateRan = $('#dateField').val();
//creating the new row to be added with a button to clear the entry
var new_row = '<tr><td>'+distanceRan+'</td><td>'+timeRan+'</td><td>'+dateRan+'</td>'+'<td>'+'<button id="clearRow">Clear Entry'+'</button></td></tr>'
$('#diary').append(new_row);
});
});
我如何做 '#clearRow' 按鈕,刪除該錶行,它是裏面嵌套?
我想出了這段代碼,但它不能正常工作,請幫忙嗎?
$('#clearRow').on('click', function(e){
$(this).closest('tr').remove()
});
雖然我同意,一個ID是不是一個問題,因爲這裏的'this' – 2014-09-01 00:12:30
我去測試它自己,看來,你是對的!由於jQuery沒有以通常的方式使用選擇器,因此將ID作爲委託事件工作正常。的確有趣! [小提琴在這裏](http://jsfiddle.net/0awnqo81/) – Stryner 2014-09-01 00:18:28
我認爲這是最好的答案,雖然+1 – 2014-09-01 00:19:39