将jquery响应分配给最接近的tr的类名div

时间:2019-07-02 17:33:46

标签: javascript jquery html

我想在选择defect_type的相应行中的类'defects'中显示jquery的响应。 jQuery请求可以正常工作并收到响应,但既不能显示在td部分,也不能显示在t的div内部。我在成功部分中编写的代码行不起作用。

<html>
    <body>
        <table>
            <tr>
                <td>
                    <select class="form-control defect_type" onChange="get_defects(this.value)">
                    <option>1</option>
                    <option>2</option>                                                   
                    </select>
                </td>   
                <td class="defects"></td>
        </tr>
        <tr>
            <td>
                <select class="form-control defect_type" onChange="get_defects(this.value)">
                    <option>1</option>
                    <option>2</option>                                                   
                </select>
            </td>   
            <td class="defects"></td>
        </tr>
    </body>
    <script>    
        $(".defect_type").change(function(){
            if(this.value==""){
                alert("Select Defect Type");
                return;
            }

            $.ajax({
                type: 'post',
                url: '../ajax/get_defects.php',
                data: {
                    defect_type: this.value
                },
                success: function (response) {
                    $(this).closest('tr').find('.defects').html(response);  
                    $(this).closest('tr').find('.defects').text(response);
                }
            });
        });
    </script>
</html>

1 个答案:

答案 0 :(得分:2)

问题:成功函数中的$(this)不涉及已更改的元素。它指的是AJAX。

解决方案:将$(this)分配给变量,然后改用该变量。

    $(".defect_type").change(function(){
        if(this.value=="") {
          alert("Select Defect Type");
          return;
       }

       var me = $(this);  // <-- create the var

       $.ajax({
           type: 'post',
           url: '../ajax/get_defects.php',
           data: {
                defect_type: this.value
           },
           success: function (response) {
               me.closest('tr').find('.defects').html(response);  // <--use the var here
               me.closest('tr').find('.defects').text(response);  // <--use the var here
           }
       });
    });