javascript - jquery $(this).attr ('id' ) 给出未定义的结果

标签 javascript jquery

<分区>

我正在尝试获取更改元素的 id 的详细信息。 但是当我试图使用下面的代码找到它时,它给出了错误。

HTML:

<input type="text" required="required" placeholder="Enter city name" class="get_neighborhood" maxlength="30" id="city" value="P" name="city" data-invalid="">
<input type="text" placeholder="State code" maxlength="2" class="get_neighborhood" required="required" id="state" value="AA" name="state">

JS:

$(document).ready(function() {
    $(".get_neighborhood").on('change',function() {
        city = $('#city').val();
        ajax_url = 'alternate_address/ajax_get_country/';

        $.ajax({
            type: 'POST', // or 'POST', whatever you want.
            dataType: 'json', // output_value will be a plain text string.
            data: {
                city: city
            },
            url: ajax_url,
            beforeSend: function(msg) {                

            },
            success: function(output_value) {
                myid = $(this).attr('id');                
                //var id=this.id;
                console.log(myid.toSource());

            },
            error: function(output_value) {
                alert('err');                    
            }
        });
    });
});

这给出了 myid 未定义的错误。 当我更改城市或州字段时。

最佳答案

尝试在该 ajax 调用之外缓存 $(this) 引用并在其中使用它。

完整代码:

$(".get_neighborhood").on('change',function() {

        city = $('#city').val();
        ajax_url = 'alternate_address/ajax_get_country/';
        _this = $(this);

        $.ajax({
            type: 'POST', // or 'POST', whatever you want.
            dataType: 'json', // output_value will be a plain text string.
            data: {
                city: city
            },
            url: ajax_url,
            beforeSend: function(msg) {                

            },
            success: function(output_value) {
                myid = _this.attr('id');                
                //var id=this.id;
                console.log(myid.toSource());

            },
            error: function(output_value) {
                alert('err');                    
            }
        });

});

关于javascript - jquery $(this).attr ('id' ) 给出未定义的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23948287/

相关文章:

Javascript - 向回调函数添加更多参数

Jquery,向元素添加类

php - data.push 不适用于 jquery

javascript - 迭代嵌套的数字键控 json 对象

javascript - 如何测试 util.inherits() 的原型(prototype)继承?

javascript - 如何将 javascript 对象转换为 utf-8 Blob 以供下载?

javascript - 是否可以在 Materializecss 上保留 card-reveal 的方向?

javascript - 使用 jQuery 设置事件菜单项

javascript - jsplumb 1.4.1 deleteEndpoint by uuid or object 示例

javascript - 脱离检测到空提示字符串的 while 循环