2011-12-12 99 views
0

我開始在這裏裏面的功能.change ...JQuery的.live使用if stament

我有這個功能...

$('.Discount').live({ 
     focusout: function() { 

     var $tr = $(this).closest('tr'); 
     var CustDiscount = $('#CustDiscount:eq(0)').val(); 
     var DiscountIS = $('.DiscountIS:eq(0)', $tr).val(); 

     if ((CustDiscount) > (DiscountIS)) { 
       (Discount) = (CustDiscount); 
     } else if 
      ((DiscountIS) > (CustDiscount)) { 
       (Discount) = (DiscountIS); 
     } else if 
      ((DiscountIS) = (CustDiscount)) { 
       (Discount) == (CustDiscount); 
     } 
      $('.Discount:eq(0)', $tr).val(Discount); 
    } 
}); 

有一個.live功能在var建立之後將使用Discount的值。如果用戶超出.Discount字段,則上述功能會根據該功能放入(Discount)。現在,我想要做的是,如果用戶輸入不同的金額到.Discount字段中,它將使用輸入的金額並覆蓋if語句。現在它默認爲if statement。什麼是實現這一目標的最佳途徑。

+1

告訴我們你打算先做什麼 –

回答

1

如果用戶輸入的值時,將被使用。如果用戶將該字段留空,則會執行if塊。那是你要的嗎?

$('.Discount').change(function() { 
    (Discount) = $(this).val(); 
    // If the field is cleared... 
    if ((Discount) == '') { 
     // ...calculate 
     if ((CustDiscount) > (DiscountIS)) { 
      (Discount) = (CustDiscount); 
     } else if ((DiscountIS) > (CustDiscount)) { 
      (Discount) = (DiscountIS); 
     } else if ((DiscountIS) == (CustDiscount)) { 
      (Discount) = (CustDiscount); 
     } 
     $(this).val(Discount); 
    } 
}); 

注意(Discount) = ('.Discount').val();在你的代碼也許應該是(Discount) = $('.Discount').val();

編輯的意見:

// Function for calculating the discount 
function calculateDiscount() { 
    if ((CustDiscount) > (DiscountIS)) { 
     return (CustDiscount); 
    } else if ((DiscountIS) > (CustDiscount)) { 
     return (DiscountIS); 
    } else if ((DiscountIS) == (CustDiscount)) { 
     return (CustDiscount); 
    } 
} 

// Set the default value 
$('.Discount').val(calculateDiscount()); 

$('.Discount').change(function() { 
    // If the field is cleared... 
    if ($(this).val() == '') { 
     $(this).val(calculateDiscount()); 
    } 
}); 
+0

不,這是不正確的,查找'jQuery.val()'的語法'編輯:現在忽略此評論這個答案已被編輯。 – jli

+0

是的,我知道,在修復之前,我指的是你的答案有'.val()=(折扣)'。編輯:argg在移動網站上沒有評論刪除按鈕,現在這個評論指的是刪除的一個.. – jli

+1

抱歉刪除評論,沒有看到您的後續評論那裏。但是我糾正了。 :) – RCE

0

嘗試成纔等:

 
$('.Discount').keyup(function() { 
    //your code here 
}); 
0

嘗試圖片事情驅動多個事件;一些行動發生,然後你迴應它。看看你的代碼,看起來你正在監視值,而不是事件。這是一個小的,但重要的區別:

// selector = find the element you're interested in: $('.Discount') 
// event = which action are you going to respond to: .change() 
$('.Discount').change(function() { 
    //your if block lives in here 
}); 

你並不需要使用.live().on() [jQuery的1.7,除非你的文本框住的動態創建行。如果是這樣的話,你可以這樣做

$('#tableName').on('change', '.Discount', function() { 
    //your if block lives here 
}); 

文檔:.on()

增加:

爲了您if,聲明,你可能需要做出以下,因爲.change()使用線檢測值何時發生變化,而不是當值相對於原始值變化時:

if ($(this).val() != this.defaultValue) { 
} 
+0

是的,這些行是動態的,這只是表單的一小部分,它可以處理幾個不同的變量,這就是if語句的原因。我使用1.6.2所以我使用.live,我也想在.Discount選擇器上的功能。 – Monty