我想实现一个基本的网站搜索页面的图像。搜索功能应该通过特定类中的每个元素,在图像的替代文本中寻找单词匹配。搜索替代文本,隐藏与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");
});
});
});
以及与的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
}
}
FYI我已经建立了JQuery的关一些StackOverflow线程,所以我绝对尽我所能找到一个类似的例子。 (类似的功能:here和here)
好了,有几个问题马上。你有多个具有相同ID的元素。这不起作用。每个id只有一个元素,每个元素只有一个id,id是唯一的。如果您想要多个样式相同或要同时选中的元素,请使用类。 – 2014-08-28 03:31:38
method =“post”将通过信息从表单发送信息。如果您要发送数据以供服务器端语言(如PHP)使用,这非常有用。在这里,你甚至不需要表单元素。 – 2014-08-28 03:33:56
我正在输入答案。您也正在使用错误的每个功能。您应该首先使用选择器来处理jQuery对象数组。 – 2014-08-28 03:40:43