jQuery Action Origination

时间:2015-02-14 02:11:35

标签: jquery

我将.addy类应用于多个输入。我不想用相同的代码编写一堆函数,所以我希望在其中包含if语句告诉函数要执行哪些部分。这取决于动作源自何处:input#address1或input#address2。

我需要帮助我的if声明。如何告诉函数#address1或#address2是否来自请求源?

$("input.addy").on('change', function(e) {
    e.preventDefault();
    var uid = $('form#data input[name=user_id]').val();
    var bid = $('form#data input[name=business_id]').val();
    if () { // If the change was made to input#address1, do the below
        var address1 = this.value;
        var data = {user_id: uid, business_id: bid, address1: address1};
        $.ajax({
            url: '/business/assignment/saveaddressone',
            type: 'POST',
            dataType: 'JSON',
            data: data,
            success: update
        })
    }
    if () { // If the change was made to input#address2, do the below

        // Here is address2 code
    }
});

3 个答案:

答案 0 :(得分:1)

您想查看已更改id的{​​{1}},您可以使用input访问该$(this).attr(id)

$("input.addy").on('change', function(e) {
    e.preventDefault();
    var uid = $('form#data input[name=user_id]').val();
    var bid = $('form#data input[name=business_id]').val();
    if ($(this).attr('id') == "address1") { //if the change was made to input#address1, do the below
        var address1 = this.value;
        var data = {user_id: uid, business_id: bid, address1: address1};
        $.ajax({
            url:'/business/assignment/saveaddressone',
            type: 'POST',
            dataType:'JSON',
            data:data,
            success: update
        })
    } 
    if ($(this).attr('id') == "address2") { //if the change was made to input#address2, do the below
        //here is address2 code
    }
});

答案 1 :(得分:1)

 e.target.id === 'address1'

 $(e.target).is('#address1')

但是,不是使用if,而是使用返回另一个函数的函数。

function doStuff(wrappedFunctionality) { return function doStuff(e) {
   var $el = $(e.target);
   //do common stuff here
   wrappedFunctionality($el);
   //do more common stuff
} }

$('#address1').on('change', doStuff(function($el) {
   //do address1 specific things
}))

$('#address2').on('change', doStuff(function($el) {
   //do address2 specific things
}))

显然,为函数提供反映其实际行为的好名称,而不是doStuffwrappedFunctionality

Learn how to write composable functions,它是如何编写惯用js的绝对核心。

答案 2 :(得分:0)

检查已更改的input.addy的ID?

if($(this).attr('id') == "address1") {
    // it is input#address1
    ...
} else if ($(this).attr('id') == "address2") {
    // it is input#address2
    ...
}