簡體   English   中英

Jquery:將變量傳遞給下一個鏈接函數,這是正確的方法嗎?

[英]Jquery: passing variable to the next chained function, is this the correct way?

我想知道這是否正確。

$('.myfilter').focus(function(){
    var length = $(this).val().length; 
    if (length == 0) {
        dosomething
    }
}).blur(function(length){
    if (length == 0) {
        dowhatever
            }
})

上面我簡化了我的代碼,我只是檢查焦點上的length == 0和輸入的模糊。 注意我如何聲明焦點的length ,但不是模糊,但是我在.blur(function(length){添加了變量名稱.blur(function(length){ 。這是在.blur獲取length的更好方法,而不必重新聲明var length = $(this).val().length; in .blur?

與此相反:

$('.myfilter').focus(function(){
    var length = $(this).val().length; 
    if (length == 0) {
        dosomething
    }
})

$('.myfilter').blur(function(length){
    var length = $(this).val().length;
    if (length == 0) {
        dowhatever
            }
})

第一個代碼塊是更好的方法嗎?

怎么沒有聲明任何變量... :)

$('.myfilter').focus(function() {
    if ( this.value.length === 0 ) {
        dosomething();
    }
}).blur(function(length) {
    if ( this.value.length === 0 ) {
        dowhatever();
    }
});

這個:

$('.myfilter').bind('focus blur', function(e) {
    if ( this.value.length === 0 ) {
        e.type === 'focus' ? dosomething() : dowhatever();
    }
});

使用變量

通常,如果需要多次使用某個值,則需要使用變量。 但是,在這種情況下,只需要一次this.value.length值(在if-header中)。 因此,您可以直接在if-header中注入此值。

$(this)vs this

為了理解何時使用哪個,您需要了解DOM元素對象和jQuery對象之間的區別。 jQuery對象是一個包裝器對象,它包含零個或多個DOM元素對象(如數組)。 重要的是要了解您只能在jQuery對象上調用jQuery方法(如.addClass() ),而不能直接調用DOM元素。

在事件處理函數內部, this值引用事件觸發的DOM元素。 現在,如果要在該DOM元素上調用jQuery方法,則需要將該DOM元素包裝在jQuery對象中 - 您可以通過編寫$(this)

$(this).addClass('selected'); // works fine
this.addClass('selected'); // throws Error

我通常會做的,如果你不想再放length ,是店length在屬性this ,然后在讀它blur的事件,就像這樣:

$('.myfilter').focus(function(){
    this.val_length = $(this).val().length; 
    if (this.val_length == 0) {
        dosomething
    }
}).blur(function(){
    if (this.val_length == 0) {
        dowhatever
    }
})

第一個代碼塊不起作用 - 傳遞給.blur()參數實際上是觸發模糊調用的事件。

另外請注意,有沒有必要使用jQuery獲得的價值,它的直接屬性this (用於輸入元素):

$('.myfilter').blur(function(ev) {
    if (this.value.length === 0) {
        // dowhatever
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM