首页 > 解决方案 > 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;

                        }
                    },

请建议做什么,因为结果代码应该在成功的情况下工作。

标签: jquery

解决方案


如果表格有多于一行,则具有多个相同元素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');

推荐阅读