2016-10-18 2 views
0

예상보다 어려워지고 있습니다. jquery 선택기를 사용하여 if/else 문을 쓰려고합니다. 어떤 라디오를 클릭했는지에 따라 메시지를 추가하고 싶습니다. 내 논리는 작동하지만 특정 라디오 버튼을 클릭하면 출력 메시지를 가져올 수 없습니다. 같은 시간에 두 결과를 모두 쉽게 인쇄 할 수 있지만 선택한 라디오에 따라 별도의 응답을 인쇄하는 방법을 알 수 없습니다.기타 라디오 옵션이있는 경우

여기 내 기능입니다 :

function imageCounter() { 

    var ballCount = 0; 
    var truckCount = 0; 

    // find images with ball in image src 
    $('img[src*=ball]').each(function() { 
    if($(this).attr('src')) { 
     ballCount+=1; 
    }  
    }); 

    // find images with truck in image src 
    $('img[src*=truck]').each(function() { 
    if($(this).attr('src')) { 
     truckCount+=1; 
    } 
    }); 

    if($(':radio[name="truckImages"]:checked')) { 
    $('#radioButtons').append("There are " + truckCount + " truck images."); 
    } else { 
    $('#radioButtons').append("There are " + ballCount + " ball images."); 
    } 
} 

HTML :

나는 문제가 $ .fn는 쿼리와 일치하는 요소의 배열을 반환 것이있을 거라고 생각
<div id="radioButtons"> 
    <input type="radio" value="truckImages" name="truckImages" id="truckImages">Fire Trucks 
    <input type="radio" value="ballImages" name="ballImages" id="ballImages"> 
    <input type="button" value="Count the Images" onclick="imageCounter()"> 
</div> 
+1

'$()'함수의 반환 값이 객체가 아니기 때문에 ($ (': radio [name = "truckImages"] : checked))' 요소가 일치 *. 또한,'if ($ (this) .attr ('src'))'는 무엇을 생각합니까? (힌트 :'src'가 비어 있지 않은 문자열이라는 것을 알기 때문에 항상 참이 될 것입니다.) – nnnnnn

+0

라디오 버튼에 대해 같은 이름을 먼저 붙여야합니다. 그러면 선택된 고유 라디오가됩니다 –

+0

if ($ 이) .attr ('src')) 특정 이미지에 대한 내 카운터를 얻을 수있는 유일한 방법은 다음과 같습니다/기본적으로 src 함께 해당 특성의 유효성을 검사하는 데 사용되는 계산됩니다. – MrJesus

답변

0

. 일치하는 요소가 없으면 빈 배열을 반환합니다. 자바 스크립트에서 !![]true을 반환합니다. 여기에서, 당신은 .length

if($(':radio[name="truckImages"]:checked').length) { 
    $('#radioButtons').append("There are " + truckCount + " truck images."); 
    } else { 
    $('#radioButtons').append("There are " + ballCount + " ball images."); 
    } 

또는

if($(':radio[name="truckImages"]').is(':checked')) { 
    $('#radioButtons').append("There are " + truckCount + " truck images."); 
    } else { 
    $('#radioButtons').append("There are " + ballCount + " ball images."); 
    } 

는 사실, 난 당신이 $ ('IMG')의 각 함수를 호출 할 필요가 있다고 생각하지 않습니다 사용해야합니다.

function imageCount() { 
    var type = $(':radio:checked')).attr('name').replace(/Images$/, ''); 
    var count = $('img[src*=' + type + ']').length; 
    $('#radioButtons').after("There are " + count + " " + type + " images."); 
} 
관련 문제