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);
}
}
}
: 지금 질문하는 사람들을 위해 더 많은 세부 사항을 추가했습니다. 모든 것이 혼란스럽게되면 죄송합니다.
일을해야한다고 생각
있습니까
라이브러리를 사용하지 않으시겠습니까? (예 : jQuery) – Yoshi"googleDisplay"HTML 요소는 어디에 있나요? 그러한 요소가없는 경우, "getElementById()"의 null 결과는 놀라운 것이 아닙니다. – Pointy
당신이 성취하려는 것을 분명히하지 못합니다, 미안 해요. 코드에서 수행 할 작업을 정확히 명시 할 수 있습니까? 감사합니다 – tinyd