2011-12-14 3 views
1

HTML 요소를 표시하거나 숨기려면 확인란을 선택하려고하지만 가능한 한 효율적으로 만들려고합니다 (하나의 함수를 재활용하고 사용하도록 설정하는 중입니다. 수동으로 정적으로 고유 한 기능을 작성하는 것보다 진화해야 함).재활용 가능한 함수 만들기 및 문자열을 변수 이름으로 변환

저는 이미 한 번만 성공했지만 약간 다른 시나리오 ("JavaScript Extract - Working Recycled Function"포함)에서이 새로운 시나리오 ("JavaScript Extract - Not Working Recycled" 기능). 내가 할 수있는 일을 청소했지만, 이번에는 어려움을 겪고있다. 내 뇌는 다른 문제를 해결하는 데 몇 시간이 걸렸다. 나는 이것을 사용하기 위해 여러 가지 요소를 기다리고있다. 지금은 그냥 먼저 구글 요소와 작동하도록하기 위해 노력하고있어.

HTML 추출

<div id="googleContainer"> 
    <input type="text" id="googleSearchBox" title="Google Search" class="searchBox" /> 
    <input type="button" id="googleSearchButton" onClick="execSearchWithClick(this.id)" /> 
</div> 
<input type="checkbox" id="googleCheck" checked="checked" onClick="setPref(this.id)"/> 

자바 스크립트를 추출- 작동하지 않음 재활용 기능

var googleDisplay = true; 
function setPref(id){ 
    alert(id) //Check ID 
    var checkboxDisplayString = document.getElementById(id.replace("Check", "Display")); //Convert "googleCheck" to "googleDisplay" to match boolean variable 
    alert(checkboxDisplayString) //Null value reply 
    var checkboxDisplayVar = checkboxDisplayString //Convert (what I suspect to be) String to variable name 
    alert(checkboxDisplayVar) //Null value reply 

    if (id == "googleCheck" && checkboxDisplayVar == true){ 
     checkboxDisplayVar = false; 
     applyPref(); 
    } else { 
     checkboxDisplayVar = true; 
     applyPref(); 
    } 
} 

function applyPref(){ 
    if (googleDisplay == true){ 
     document.getElementById("googleContainer").style.display = "block"; 
    } else { 
     document.getElementById("googleContainer").style.display = "none"; 
    } 
} 

편집 - 재활용 기능을 작동 자바 스크립트를 추출

var googleHome = "http://www.google.com/"; //Set home page 
var googleSearchURL = googleHome + "search?q="; //Prime search URL 
function execSearchWithClick(id){ 
    alert(id) //Check ID 
    var searchBox = document.getElementById(id.replace("Button", "Box")); //Convert "googleSearchButton" to "googleSearchBox" to match target element 
    var searchQuery = searchBox.value; //Extract value from converted string-to-variable 

    if (searchQuery == ""){ 
     if (id == "googleSearchButton") { 
      window.open(googleHome); 
     } //I would use "if(condition && condition)" rather than nested IFs here, but I plan to use ELSE IF very soon 
    } else { 
     if (id == "googleSearchButton") { 
      window.open(googleSearchURL + searchQuery); 
     } 
    } 
} 

: 지금 질문하는 사람들을 위해 더 많은 세부 사항을 추가했습니다. 모든 것이 혼란스럽게되면 죄송합니다.

+0

일을해야한다고 생각

있습니까

라이브러리를 사용하지 않으시겠습니까? (예 : jQuery) – Yoshi

+0

"googleDisplay"HTML 요소는 어디에 있나요? 그러한 요소가없는 경우, "getElementById()"의 null 결과는 놀라운 것이 아닙니다. – Pointy

+0

당신이 성취하려는 것을 분명히하지 못합니다, 미안 해요. 코드에서 수행 할 작업을 정확히 명시 할 수 있습니까? 감사합니다 – tinyd

답변

1

자바 스크립트 : 이유는

function setPref(id){ 
     var checkbox = document.getElementById(id); 
     applyPref(checkbox.checked);  
    } 

    function applyPref(show){ 
     if (show){ 
      document.getElementById("googleContainer").style.display = "block"; 
     } else { 
      document.getElementById("googleContainer").style.display = "none"; 
     } 
    } 
내가 뭔가를 누락 될 수 있습니다,하지만 난 같은 위

+0

당신은 선생님입니다. 그것은 일종의 일이었습니다. 나는 그것을 수정해야만했다 : function setPref (id) { var checkbox = document.getElementById (id); applyPref (checkbox.checked, id); } function applyPref (show, id) { \t var 컨테이너 = document.getElementById (id.replace ("Check", "Container"))); \t if (show) { container.style.display = "block"; } else { container.style.display = "none"; } } 확인란을 선택하면 아무 문제가 없습니다. 하지만 그래, 고마워! –

+0

도움이 되니 기쁩니다. 나는 당신의 '작동하지 않는'버전에서 JavaScript 변수의 이름과 페이지의 요소 ID 사이에 약간의 혼란이 있다고 생각하지만, 어쨌든, 당신이 지금 거기에있는 것처럼 보입니다. 행운을 빕니다! – tinyd

0

나는 변수 이름을 변환하는 대신 변수를 함수 onCLick에 전달하는 대신 다음과 같이합니다.

<div id="one" style="width:100%;height:100px;background-color:#000;"></div> 
<form> 
<input id="one-check" type="checkbox" name="one" onclick="showOrHide('one');"> 
</form> 
<div id="two" style="width:100%;height:100px;background-color:#000;"></div> 
<form> 
<input id="two-check" type="checkbox" name="two" onclick="showOrHide('two');"> 
</form> 

이 내 시도 될 것

function showOrHide(id){ 

alert(id); 

var checkBox = document.getElementById(id+'-check'); 

if (checkBox.checked == 1){ 

document.getElementById(id).style.display = "none"; 

} else { 

document.getElementById(id).style.display = "block"; 

} 

} 
+0

내 전체 코드를 편집하는 대신 여기에 넣습니다. http://jsfiddle.net/LyTmb/1/ 많은 것을 할 것 같지 않았습니다 .. 내가 이해하는 코드를 선호합니다. 나는 거기에서 벌어지고있는 일을 실제로 얻지 못한다. : L –

+0

죄송합니다, 나는 당신이 체크 박스를 사용하고 있었다는 것을 믿지 않았고 그것을 업데이트했습니다. >> http://jsfiddle.net/5ZtfG/ – Wez

+0

시간과 노력에 감사 드리며, 제 문제는 해결되었습니다. 하지만 네 길은 너무 좋았어! :) 당신도 jsfiddle에 데려 가기를 바랍니다. 그것은 꽤 유용한 도구입니다! : D –

관련 문제