2016-11-22 1 views
-1

jQuery 문에서 javascript 함수를 호출하는 데 문제가 있습니다. 자바 스크립트 함수 안에 jQuery가 작동하지 않는 것 같습니다. 구문 오류가 있습니까? 나는 filterImage 기능을 내부에 더 많은 기능을 필요로하기 때문에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(); 
    }); 
});  

구조가 변경되고, 브래킷 내부의 문이 제대로 실행하지 못했습니다 :

코드

이로 일했다.

$(".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

당신은 아마 대신이 일을 의미 : 내가 대신 함수 내에서, 클릭 이벤트 주위 ready 이벤트를 이동 한

$(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"); 
    } 
} 

알 수 있습니다.

또한 사용자가 클릭 한 요소를 함수에 전달하지 않았기 때문에 $(this)을 사용할 수 없습니다. 이 문제를 해결하고 클릭 한 요소를 filterImage() 함수의 $e으로 캐스팅했습니다.

+0

이것은 훌륭한 대답입니다. $ (document) .ready()는 문서 준비가되면 (페이지가 열릴 때마다) 해고 될 것입니다. 함수 안에 넣으면 안됩니다. – EvSunWoodard

+0

제거하려는 경우 요소에 클래스가 포함되어 있는지 여부를 명시 적으로 확인할 필요가 없습니다. – DinoMyte

+0

물론, 만약 당신이 계획하고있는 유일한 일은 그것을 제거하는 것입니다. 그러나 위의 함수에서'hasClass'는': checked'의 대용품으로 작동합니다 - 이것은 전체 함수의 주요 조건 연산자입니다. – Santi

관련 문제