2016-11-22 141 views
-1

無法通過jQuery語句調用javascript函數。似乎JavaScript函數內的jQuery不起作用。有沒有語法錯誤?無法使用jQuery調用javascript函數

的代碼工作,因爲這:

jQuery(function ($) { 
    // init the state from the input 
    $(".image-checkbox").each(function() { 
     if ($(this).find('input[type="checkbox"]').first().attr("checked")) { 
      $(this).addClass('image-checkbox-checked'); 
     } 
     else { 
      $(this).removeClass('image-checkbox-checked'); 
     } 
    }); 

    // sync the state to the input 
    $(".image-checkbox").on("click", function (e) { 
     if ($(this).hasClass('image-checkbox-checked')) { 
      $(this).removeClass('image-checkbox-checked'); 
      $(this).find('input[type="checkbox"]').first().removeAttr("checked"); 
     } 
     else { 
      $(this).addClass('image-checkbox-checked'); 
      $(this).find('input[type="checkbox"]').first().attr("checked", "checked"); 
     } 
     e.preventDefault(); 
    }); 
});  

結構改變,因爲我需要的filterImage函數內部功能更加完善,括號內的語句未能正常運行。

$(".image-checkbox").on("click", function(e) { 
     filterImage(); 
    }); 

function filterImage() { 
    $(document).ready(function() { 
     if ($(this).hasClass('image-checkbox-checked')) { 
      $(this).removeClass('image-checkbox-checked'); 
      $(this).find('input[type="checkbox"]').first().removeAttr("checked"); 
     } 
     else { 
      $(this).addClass('image-checkbox-checked'); 
      $(this).find('input[type="checkbox"]').first().attr("checked", "checked"); 
     } 
    }); 
} 
+0

將'$(document).ready(function(){'圍繞您的事件處理程序並將其從函數中移除 – empiric

+0

控制檯中的任何錯誤?函數或單擊事件本身執行? – empiric

+0

@empiric,Thanks爲了您的及時回覆!從我所看到的,if-else括號內的語句運行不正常,因此它總是進入else部分。 – Victor

回答

3

你可能爲了做這個:

$(document).ready(function() { 
    $(".image-checkbox").on("click", function() { 
     filterImage(this); 
    }); 
}); 

function filterImage(e) { 
    var $e = $(e); 
    if ($e.hasClass('image-checkbox-checked')) { 
     $e.removeClass('image-checkbox-checked'); 
     $e.find('input[type="checkbox"]').first().removeAttr("checked"); 
    } else { 
     $e.addClass('image-checkbox-checked'); 
     $e.find('input[type="checkbox"]').first().attr("checked", "checked"); 
    } 
} 

注意到我感動周圍的單擊事件您ready事件,而不是內部的功能。

此外,您使用$(this)不會奏效,因爲您沒有將單擊元素傳遞給該函數。我解決了這個問題,並在filterImage()函數中將點擊元素放置爲$e

+0

這是一個很好的答案。請注意$(document).ready()是一個事件,它將會文檔準備就緒時會被解僱(當頁面打開時或多或少)。它不應該放在一個函數中。 – EvSunWoodard

+0

如果您計劃刪除某個元素,則顯式不需要檢查該元素是否包含該類。 – DinoMyte

+0

當然,如果您計劃做的* only *事情是將其刪除。但是上面的函數中的'hasClass'可以代替':checked' - 它是整個函數的主要條件運算符。 – Santi