我正在尝试实现一个基本的网站搜索图像页面。搜索功能应该遍历特定类中的每个元素,以在图像的替换文本中查找单词匹配。
我认为我的问题是将功能绑定到表单提交,但我似乎无法弄清楚我哪里出错了。
我试过 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");
});
});
});
与 JavaScript (小提琴: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
}
}
仅供参考我已经通过一些StackOverflow线程构建了JQuery,所以我一定尽力找到类似的例子。 (类似函数:here和here)
答案 0 :(得分: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();
}
});
});