在Jquery attr上使用这个类

时间:2016-06-22 07:31:02

标签: javascript jquery css

这是

HTML

<div id="myForm" class="myForm row">
    <div class="form-group row">
        <div class="col-lg-12">
            <div class="col-md-4">
                <label>Nama Teman *</label>
                <input type='text' name='name_friend[]' id='name_friend[]' class='form-control name_friend[]' placeholder='Nama' required />
            </div>
            <div class="col-md-4">
                <label>Nomor Handphone*</label>
                <input type='text' name='nomor_telepon[]' id='nomor_telepon[]' class='form-control nomor_telepon[] telepon phone-email' placeholder='Nomor Telepon' required />
            </div>
            <div class="col-md-4">
                <label>Email</label>
                <input type='email' name='email_friend[]' id='email_friend[]' class='form-control email_friend[] phone-email' placeholder='Email' />
            </div>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-lg-12">
            <div class="col-md-4">
                <label>Nama Teman *</label>
                <input type='text' name='name_friend[]' id='name_friend[]' class='form-control name_friend[]' placeholder='Nama' required />
            </div>
            <div class="col-md-4">
                <label>Nomor Handphone *</label>
                <input type='text' name='nomor_telepon[]' id='nomor_telepon[]' class='form-control nomor_telepon[] telepon phone-email' placeholder='Nomor Telepon' required />
            </div>
            <div class="col-md-4">
                <label>Email</label>
                <input type='email' name='email_friend[]' id='email_friend[]' class='form-control email_friend[] phone-email' placeholder='Email' />
            </div>
        </div>
    </div>
</div>

的jQuery

$(".phone-email").blur(function(e) {
    var param = $(this).val();
    var url = "<?php echo base_url('/Campaign/check_data');?>";
    $.ajax({
        url: url,
        type: "POST",
        data: {
            param: param
        }
    }).done(function(d) {
        var obj = JSON.parse(d);
        if (obj.status == "0") {
            alert(obj.message);
            $("#add-friend").attr('disabled', 'disabled');
            $(this).attr('style', 'border: 2px solid #a94442');
        } else if (obj.status == "1") {
            $("#add-friend").removeAttr('disabled');
        }
    });
});

这个代码没有正常工作,元素类没有边框,我想如果status = 1那么输入会给出红色边框,但我的代码不能正常工作

$(this).attr('style', 'border: 2px solid #a94442');

1 个答案:

答案 0 :(得分:4)

您的实施问题是当前元素上下文this不是phone-email

的完整方法中的.ajax()元素

使用

$(".phone-email").blur(function (e) {
    //Cache the this context in a variable
    var _this = $(this); 

    $.ajax().done(function(d){
        //Use the variable
        _this.attr('style', 'border: 2px solid #a94442');

        //You can use .css() method to change the CSS rule
        //_this.css('border', '2px solid #a94442');
    }); 
}); 

注意:我删除了代码,只保留了所需的部分。