简体   繁体   English

Javascript在用户搜索时从数组生成内容

[英]Javascript generating content from an array on user search

I'm having issues dynamically creating content from an array of images. 我在动态创建从图像阵列内容的问题。 What I want to happen is that when keywords are entered into the searchbar (try "joyride" or "nick"), all of the images that match the keywords show up. 我希望发生的是,当关键字输入到搜索栏(尝试“兜风”或“缺口”),所有符合关键字的图像的显示。 Currently, only one image shows up, and it doesn't necessarily match the keyword. 目前,只有一个图像显示出来,它不一定匹配关键字。 I think I'm going wrong with the javascript function - I feel like I shouldn't be using innerHTML to create the photos, especially because when the keyword is deleted, it just leaves the one image. 我想我会错的javascript函数 - 我觉得我不应该使用innerHTML来创建的照片,特别是因为当关键词被删除,它只是离开一个图像。

Would it be easier to do it all in jQuery/javascript, instead of generating the initial gallery of images in jQuery and trying to do the filtering in javascript? 会是更容易做到这一切的jQuery / JavaScript的,而不是生成图像的jQuery的初始画廊,努力做JavaScript中的过滤? I'm lost. 我迷路了。

http://scf.usc.edu/~uota/itp301/final/odc-photos.html http://scf.usc.edu/~uota/itp301/final/odc-photos.html

This is a working version of the page, with the arrays and other code that I am using. 这是该页面的有效版本,包含我正在使用的数组和其他代码。

Thanks in advance! 提前致谢!

 $(document).ready(function(){
    for(var i = 0; i < src.length; i++){
    var content = "<div class='pics' id='imagesection" + i + "'>";
    content += "<div class='images'><img class='imagesfiles' height='133px' width='200px' src='" + src[i] + "'></div>";
    content += "</div>";
    $("#gallery").append(content).hide().fadeIn(250);
}

});

var songSearch = function(keyword){
var foundFlag = false;
var content = "";

for (var i = 0; i < src.length; i++){
if (tags[i].toLowerCase().indexOf(keyword) != -1 || keyword == "") {
    content = "<div class='pics' id='imagesection" + i + "'>";
        content += "<div class='images'><img class='imagesfiles' height='133px' width='200px' src='" + src[i] + "'></div>";
    content += "</div>";

        findFlag = true;
    }

}

if(findFlag){
document.getElementById("gallery").innerHTML = content;
}
else{
    content = "Your search did not return any results.";
}

 }

</script>

It looks like the problem is on this line in the songSearch function: 看起来问题出在songSearch函数的这一行上:

content = "<div class='pics' id='imagesection" + i + "'>";

You are redefining the variable content instead of concatenating it. 您正在重新定义变量内容,而不是对其进行串联。 This way it will always be just the last image. 这样,它将始终只是最后一张图像。 Try changing it to: 尝试将其更改为:

content += "<div class='pics' id='imagesection" + i + "'>";

There is also have a variable inside the songSearch function called foundFlag that is later referenced as findFlag. songSearch函数内部还有一个名为foundFlag的变量,该变量以后称为findFlag。 That shouldn't be causing the issue though. 但这不应该引起问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM