2016-06-16 4 views
0

텍스트로 채워지는 적색 십자가가있는 작은 이미지를 각각 동적으로 생성하는 두 개의 입력 필드가 있습니다. 아이디어는 사용자가 그 이미지를 클릭하여 텍스트를 지울 수 있다는 것입니다. javacript 코드는 이미지의 고도 값과 입력 상자의이름 속성 인 유일한 차이점과 정확히 동일합니다. 중첩 된 jQuery 함수에 변수 전달하기

<!DOCTYPE html> <html> <head> <script language="javascript" type="text/javascript" src="js/jquery-2.1.3.min.js"></script> <script> $(document).ready(function() { $("input[type='text']").keyup(function(){ var alt = "clear"+$(this).attr("name"); if($(this).val() && !$("img[alt='"+alt+"']").length){ $(this).after("<img src='images/cross.png' alt='"+alt+"'/>"); } }); $(document).on('click', 'img[alt="clearsource"]' , function(){ $("input[name='source']").val(''); $(this).remove(); }); $(document).on('click', 'img[alt="clearlocation"]' , function(){ $("input[name='location']").val(''); $(this).remove(); }); }); </script> </head> <body> <form> <input type="text" name="source" placeholder="Source" /><br /> <input type="text" name="location" placeholder="Location" /> </form> </body> </html> 

가 나는 두 개의 변수를 전달하고 두 번 호출 할 수있는 재사용 가능한 기능을 만들고 싶었다. 이것은 내 시도이지만 작동하지 않습니다. 누군가 제발 도와 줄 수 있니? 범위 문제입니까? 사전에 https://jsfiddle.net/2bk86w4y/

<script> 
$(document).ready(function() { 

    $("input[type='text']").keyup(function(){ 
     var alt = "clear"+$(this).attr("name"); 
     if($(this).val() && !$("img[alt='"+alt+"']").length){ 
      $(this).after("<img src='images/cross.png' alt='"+alt+"'/>"); 
     } 
    }); 

    // == The function below replaces the duplicate functions in the previous code block. 
    // == Unfortunately it doesn't work. Please help :(

    function clearBox(inputname,imagealt){ 
     $(document).on("click", "img[alt='"+imagealt+"']" , function(){ 
      $("input[name='"+inputname+"']" ).val(''); 
      $(this).remove(); 
     }); 
    } 

    clearBox("clearsource","source"); 
    clearBox("clearlocation","location"); 
}); 
</script> 

많은 감사 :

다음은 JSFiddle 버전입니다!

+4

A [mcve] 좋은 것입니다! –

+1

일하지 않음으로써 당신은 무엇을 의미합니까? 이러한 변수 인'inputname'과'imagealt'는 이제 그 함수에 대한 범위를 가져야하며 조회 할 수 있어야합니다. 그것은 잘 작동하는 것 : https://jsfiddle.net/1be5wpte/ – AtheistP3ace

+0

안녕 얘들 아, 당신에게 더 나은 아이디어를 줄 동일한 문제와 간단한 예제 코드를 업데이 트했습니다. 이게 도움이 되길 바란다! 앞으로 귀하의 지원을 기대 : – Haret

답변

1

매개 변수의 방향이 잘못되었습니다.

https://jsfiddle.net/daveSalomon/2bk86w4y/1/

clearBox("clearsource", "source"); 
clearBox("clearlocation", "location"); 

// should be... 

clearBox("source", "clearsource"); 
clearBox("location", "clearlocation"); 
+1

데이브, 당신은 굉장합니다! 나는 STUPID 실수가 xD 때문에 여기 웃고 있습니다. 정말 고맙습니다! 정말 정말 고마워! – Haret