2014-08-28 2 views
0

이미지 페이지에 대한 기본 사이트 검색을 구현하려고합니다. 검색 기능은 이미지의 대체 텍스트에서 단어 일치를 찾는 특정 클래스의 각 요소를 거쳐야합니다.검색 대체 텍스트, jQuery/JavaScript와의 불일치를 숨기기

내 문제는 양식을 제출하는 기능을 바인딩하는 것 같지만 잘못된 위치를 파악할 수없는 것 같습니다.

내가 jQuery를 이것을 시도 (바이올린 : http://jsfiddle.net/u2oewez4/)뿐만 아니라 자바 스크립트와 같은

$(document).ready(function(){ 
$("#search-form").click(function() { 

var searchQuery = "Text"; 

$.each('.single-image', function(){ 
$(this).children("img").attr("alt"):contains(searchQuery).hide("slow"); 
}); 
}); 
}); 

(바이올린 : http://jsfiddle.net/m3LkxL1c/)

function submitSearch(){ 

// create regex with query 
var searchQuery = new RegExp(document.getElementById('search-input').value); 

// create array of content to look for query in  
var content = document.getElementsByClassName("single-image"); 

// create an array to put the results to hide in 
var hideResults = [];  

var imagesToHide = document.getElementsByClassName("single-image-hide"); 

// get the current display value 
var displaySetting = imagesToHide.style.display;    


for (i=0; i<content.length; i++) { 
if (! searchQuery.test(content[i].firstChild.firstChild.nodeValue)) { 

// if the query not found for this result in query 
hideResults.push(content[i]);   

// push to the hideResults array 
content[i].className = "single-image-hide"; 

// change class name so CSS can take care of hiding element 
document.getElementById("form-success").style.display = 'inline-block'; 
alert(searchQuery); // for debugging 
return false; // results will not stick without this? 
} 
} 

// set display to hidden 
if(displaySetting == 'inline-block'){ 
imagesToHide.style.display = 'none';   // map is visible, so hide it 
} 
else{ 
imagesToHide.style.display = 'inline-block'; // map is hidden so show it 
} 
} 

는 참고로 나는 떨어져 JQuery와 구축 몇 가지 StackOverflow 스레드가 있으므로 비슷한 예제를 찾기 위해 최선을 다했습니다. (비슷한 기능 : herehere)

+0

좋아, 몇 가지 문제. 동일한 ID를 가진 요소가 여러 개 있습니다. 이것은 작동하지 않습니다. id 당 하나의 요소 만, 요소 당 하나의 id 만, id는 고유합니다. 동일한 스타일을 가진 여러 요소를 원하거나 동시에 선택하려는 경우 클래스를 사용하십시오. –

+0

method = "post"는 양식을 통해 게시물을 통해 정보를 보냅니다. PHP와 같은 서버 측 언어에서 사용할 데이터를 보내는 경우 유용합니다. 여기에서는 양식 요소가 필요하지 않습니다. –

+0

지금 답변을 입력하고 있습니다. 또한 각 기능을 잘못 사용하고 있습니다. 먼저 jQuery 객체 배열에 selector를 사용해야합니다. –

답변

0

좋아, 다양한 버그 수정, 대부분 내가 코멘트에서 언급했기 때문에 이미 놓치지 않았으므로. jQuery documentation의 세부 정보를 훨씬 자세히 읽어야합니다. 그러면 each 기능을 잘못 사용하는 등 많은 문제를 해결할 수 있습니다. 다른 것들은 시간이 지날 것입니다. 공부를 계속하고 문서를 읽으십시오.

$("#search-form").click(function() { 
    //this gets the val for the search box, then puts the Imgs in a variable so we don't have to use the selector multiple times. Selectors are expensive time-wise, stored variables are not. 
    var searchQuery = $("#search-text").val(), 
     singleImgs = $('.single-image'); 

    //you have to show the images for each new iteration, or they'll remain hidden 
    singleImgs.show(); 
    singleImgs.each(function(){ 
     //get alt attribute 
     var thisAlt = $(this).find("img").attr("alt"); 
     //if thisAlt does not contains searchQuery (use > instead of === for does) 
     if(thisAlt.indexOf(searchQuery) === -1){ 
      $(this).hide();     
     } 
    }); 
}); 
스르르

working fiddle

+0

감사합니다! 이것은 매우 도움이되며 완벽하게 작동합니다. JQuery에서의 그런 작은 경험으로 생각하지 못한 단계가 있기 때문에 주석에 컨텍스트를 추가해 주셔서 감사합니다. – Michelle