jquery - Jquery:如何为当前 TD 设置一些值
问题描述
我有一个包含几列和几行的 html 表。每行都有一个 TD 中的按钮。当单击按钮时,我想将一些文本设置为当前或最近的按钮 td。
这种方式我尝试过,但单击按钮时没有任何反应。
$('#tblAppointments').on('click', '#btnbook', function () {
$(this).closest('td').html('Booked');
$(this).parent.html('Booked');
});
表格 HTML
<table id="tblAppointments" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Doctor Name</th>
<th scope="col">Available Date</th>
<th scope="col">Available Time</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="hdndocid" value="1" type="hidden">
<input id="hdnpatientemail" value="popy@gmail.com" type="hidden">Dr Debasis Saha</td>
<td>27/05/2018</td>
<td>10:10 A.M.</td>
<td><button id="btnbook" type="button" class="btn btn-info">Book Now</button></td>
</tbody>
</table>
此代码不起作用。我想从 td 中删除按钮并设置一些文本,如 Booked。我的代码有什么错误。
编辑
看看我是如何做完整代码的
$('#tblAppointments').on('click', '.btnbook', function () {
var rowid = $(this).closest('tr').find("input[id*='hdndocid']").val();
var email = $(this).closest('tr').find("input[id*='hdnpatientemail']").val();
//$(this).closest('td').html('Booked');
var baseurl = '@ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
//alert(baseurl);
$.ajax({
url: baseurl,
type: 'POST',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ email: email, rowid: rowid }),
success: function (data, textStatus, xhr) {
if(data=='SUCCESS');
{
$(this).closest('td').html('Booked');
return false;
}
},
error: function (xhr, textStatus, errorThrown) {
var err = eval("(" + xhr.responseText + ")");
alert('Error ' + err.Message);
console.log(textStatus);
}
}).done(function () {
});
});
如果我在按钮单击顶部写下这些行,那么它正在工作
$(this).closest('td').html('Booked');
return false;
但是当我把这条线放在jquery ajax成功中时它就不起作用了
success: function (data, textStatus, xhr) {
if(data=='SUCCESS');
{
$(this).closest('td').html('Booked');
return false;
}
},
请建议做什么,因为结果代码应该在成功的情况下工作。
解决方案
如果表格有多于一行,则具有多个相同元素id
是无效的 html,您应该改用类选择器:
<td>
<button type="button" class="btn btn-info btnbook">Book Now</button>
</td>
<script>
$(function(){
$('#tblAppointments').on('click', '.btnbook', function () {
$(this).closest('td').text('Booked');
});
});
</script>
($(this).parent.html('Booked');
如果你确实使用它,应该是,$(this).parent().html('Booked');
但无论如何.closest('td')
都会选择最靠近'td'
链的,所以它是不需要的,基于你的 html)。
如果您正确引用了 jQuery,并且您没有另一个带有 . 的元素,那么id = tblAppointments
这应该可以工作。
根据您更新的代码,将此代码放在前面$.ajax
:
var _this = $(this);
并将成功函数更改为:
_this.closest('td').html('Booked');
推荐阅读
- visual-studio-debugging - 无法进入 PresentationFramework
- scala - TwitterServer (Finch/Finagle) 似乎阻止了 api 调用,直到它完成计算
- javascript - 如何循环 Angular FormArray - 当前设置为循环中的最后一项
- google-cloud-data-fusion - Google Cloud Data Fusion - Dataproc 配置突然停止,没有任何错误消息
- c++ - 三角形位置的颜色
- javascript - 如何在 Javascript 中获取地图数组以在下拉列表中打印
- c# - 如何使用 HttpClient 发布一个简单的 POCO?
- google-chrome-devtools - 一旦在窗口中检测到变量,chrome就可以运行代码吗?
- android - 项目点击上的 RecyclerView 启动错误的活动
- python - 如何从源代码使用 pbr 版本?