隐藏未输入到结果中的搜索栏 [英] Search bar that hides results that aren't typed into it

查看:94
本文介绍了隐藏未输入到结果中的搜索栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我想在本地显示/存储的唯一数据就是Apple和Car。

换句话说,如果用户类型在苹果中,结果将显示单词苹果,并隐藏单词汽车,反之亦然(目前我有一张图片和价格并链接到与每个项目相关的出价页面,但我可以将它作为一个不同的问题)。

我想用本地数据搜索栏的屏幕截图(目前无效):



示例搜索栏截图(作品):

< a href =https://i.stack.imgur.com/n1aY8.png =nofollow noreferrer> >



链接到完整项目(没有nodes_modules文件夹):dropbox.com/s/n2g5tgy2zs7q2l4/SearchBar.zip?dl=0



链接到plunker(这只显示我试图更改的搜索栏,但演示/示例搜索栏文件也在这一个中)



plnkr.co/edit/eCmNpkKHYdKgnHbXkBvg? p =预览

我试图改变的搜索栏的html代码(SearchDisplay.component.html)

 < input class =search2id =txtSearchtype =textname =serach_barsize =31maxlength =255
value =style =left:396px;顶部:153px;宽度:293px; height:26px;/>
< input class =search1type =submitname =submitionvalue =Searchstyle =padding-
bottom:20px; left:691px;顶部:153px; ()'
< script type =text / javascript>
document.getElementById('frmSearch')。onsubmit = function(){
window.location = 'document.getElementById('txtSearch')。value;
return false;
}
< / script>
'本地数据(不知道如何编码)

显示搜索结果的函数:

 var data [] = {Apple,Car}; 
SearchBarFunction()
{
//不知道如何显示数据
console.log(data);
}



 < input #term(keyup)=search(term.value)/> 
< ul>
< li * ngFor =#item of items | async> {{item}}< / li>
< / ul>



< p $>

  export class WikipediaService {
构造函数(private jsonp:Jsonp) {}
search(term:string){
let wikiUrl ='http://en.wikipedia.org/w/api.php';
var params = new URLSearchParams();
params.set('search',term); //用户的搜索值
params.set('action','opensearch');
params.set('format', 'json');
params.set('callback','JSONP_CALLBACK');
// TODO:添加错误处理
返回this.jsonp
.get(wikiUrl, {search:params})
.map(request =>< string []> request.json()[1]);
}
}

SearchDisplay.component.html的完整html代码:



<$ p $ < code>< html>
< center>
< h3>搜索和显示页面< h3>
< / center>
< p>



< / p>



< form>


< input class =search2id =txtSearchtype =textname =serach_barsize =31maxlength =255
value =style =left:396px; top:153px; width:293px; height:26px; />
< input class =search1type =submitname =submitionvalue =Searchstyle =padding-
bottom:20px; left:691px; top:153px; height: 23px/>

< script type =text / javascript>
document.getElementById('frmSearch')。onsubmit = function(){
window.location ='本地数据在这里(不知道如何编码)'+ document.getElementById('txtSearch')。值;
返回false;
}
< / script>

< p>



< / p>


< form>
< img src =alt =Applestyle =width:100px; height:100px;>
< p>
< / p>
< label for =name> Apple< / label>
< label for =name>价格:$ 1.00< / label>

< p>



< / p>
< div>




< / div>


< p>



< / p>


< form>
< img src =alt =Applestyle =width:100px; height:100px;>
< p>
< / p>
< label for =name> Car< / label>
< label for =name>价格:23,560.99美元< / label>

< p>



< / p>

< p>




< / p>

<按钮>点击此处返回页首。< / button>











< ! -
版权所有2016 Google Inc.保留所有权利。
使用此源代码受MIT风格许可证约束,
可在LICENSE文件中找到,网址为http://angular.io/license
- >

完整的SearchDisplay.component.ts代码

 从'angular2 / core'导入{Component,OnInit}; 
从'angular2 / router'导入{路由器};
从'./hero'导入{Hero};
从'./hero.service'中导入{HeroService};
从'angular2 / router'导入{RouteConfig,ROUTER_DIRECTIVES};
从'./heroes.component'中导入{HeroesComponent};
从'./hero-detail.component'导入{HeroDetailComponent};
从'./dashboard.component'导入{DashboardComponent};
从'./spreadsheeteditall.component'中导入{SpreadSheetComponent};
从'./SwitchUsers.component'中导入{SwitchUsersComponent};
从'./BiddingPage.component'导入{BiddingPageComponent};


$ b @Component({
selector:'SearchAndDisplayComponent',
templateUrl:'app / SearchDisplay.component.html',
styleUrls:['app / SearchDisplay.component.css'],
providers:[HeroService],
指令:[ROUTER_DIRECTIVES]
})



导出类SearchAndDisplayComponent {
typeChecker(){
var priceChecker = document.getElementById('price')。nodeValue.valueOf;
console.log(priceChecker);
if(isNaN(+ priceChecker))
{
alert(输入的价格不是数字,请输入数字);
}
var data [] = {Apple,Car};
SearchBarFunction()
{
//不知道如何显示数据
console.log(data);
}


GoToBiddingWebpage()
{
//不知道这段代码是否正确
returnhttp:// localhost :3000 / SearchDisplay / BiddingPage;


retry()
{
let ticks $ = Observable.interval(5000);
let response $ = XMLHttpRequest.get('somebadconnection.json')
.retry(3)
.map(res => res.json());

let response =
ticks $
.flatMapLatest((=)=> XMLHttpRequest.get('stock.sjon'))
.map(res => ; res.json());

let stockPoller =回复$ .subscribe(res => console.log(res));


回应$ .subscrbie(
res => console.log(res),
err => console.log('couldnt connect!') );

stockPoller.unsubscribe();

}
* /
英雄:Hero [];
selectedHero:Hero;

myFunction(){

}


构造函数(private _heroService:HeroService,private _router:Router){}

getHeroes(){
this._heroService.getHeroes()。then(heroes => this.heroes = heroes);


gotoDetail(){
this._router.navigate(['HeroDetail',{id:this.selectedHero.id}]);
}

ngOnInit(){
this.getHeroes();
}

onSelect(英雄:英雄){this.selectedHero =英雄; }
}


解决方案

试试这个: p>

 < input class =search1type =submitname =submitionvalue =Searchstyle =padding- 
bottom:20px; left:691px; top:153px; height:23px(click)=clicked()/>

并且在您的课程中:

<$ p $ (不知道如何编写这个代码)'+ document.getElementById('txtSearch'');
clicked(){
window.location.href ='local data here )。值;
返回false;
}
...

虽然我认为你需要制作一个ajax调用从服务器获取结果(或者可能是前5)?如果是这样,您需要使用angular2注入:

  ... 
import {HTTP_PROVIDERS,Http} from '@角/ HTTP';
...
@Component({
...
providers:[HTTP_PROVIDERS]
...
})
导出类测试{
...
构造函数(private http:Http){}
...
clicked(){
this.http.get('server address返回一个json结果',(data)=> {
//用数据做某件事情,你可能需要绑定到绑定到列表结果的另一个数组属性
});
返回false;
}
...
}


So far the only data I want to be displayed/stored locally are the words "Apple" and "Car."

In other words, if the user types in "apple", the results would display the word "apple" and hide the word "car" and vice versa (currently I have a picture and price and link to the bidding page associated with each item but I could post that as a different question).

Screenshot of the search bar I want to use with local data (currently does not work):

Screenshot of example search bar (works):

Link to full project (without nodes_modules folder): dropbox.com/s/n2g5tgy2zs7q2l4/SearchBar.zip?dl=0

Link to plunker (this only displays the search bar I'm trying to change, but the demo/example search bar files are in this one too)

plnkr.co/edit/eCmNpkKHYdKgnHbXkBvg?p=preview

The html code of the search bar I'm trying to change (SearchDisplay.component.html)

    <input class="search2" id="txtSearch" type="text" name="serach_bar" size="31" maxlength="255"       
    value="" style="left: 396px; top: 153px; width: 293px; height: 26px;" />
    <input class="search1" type="submit" name="submition" value="Search" style=" padding-  
    bottom:20px; left: 691px; top: 153px; height: 23px" />
<script type="text/javascript">
    document.getElementById('frmSearch').onsubmit = function() {
        window.location = 'local data here (not sure how to code this)' + document.getElementById('txtSearch').value;
        return false;
    }
</script>

The function to display the results of the search:

  var data[] = {"Apple, Car"};
   SearchBarFunction()
   {
     //not sure how to display the data
     console.log(data);
   }

HTML Code of search example that works:

<input #term (keyup)="search(term.value)"/>
    <ul>
     <li *ngFor="#item of items | async">{{item}}</li>
    </ul>

Code of the function of example that works:

export class WikipediaService {
  constructor(private jsonp: Jsonp) {}
  search (term: string) {
    let wikiUrl = 'http://en.wikipedia.org/w/api.php';
    var params = new URLSearchParams();
params.set('search', term); // the user's search value
    params.set('action', 'opensearch');
    params.set('format', 'json');
    params.set('callback', 'JSONP_CALLBACK');
    // TODO: Add error handling
    return this.jsonp
               .get(wikiUrl, { search: params })
               .map(request => <string[]> request.json()[1]);
  }
}

The full html code of SearchDisplay.component.html:

<html>
    <center>
<h3>Search and Display Page</h3>
</center>
<p>



 </p>



  <form>


<input class="search2" id="txtSearch" type="text" name="serach_bar" size="31" maxlength="255"       
value="" style="left: 396px; top: 153px; width: 293px; height: 26px;" />
<input class="search1" type="submit" name="submition" value="Search" style=" padding-  
bottom:20px; left: 691px; top: 153px; height: 23px" />

<script type="text/javascript">
    document.getElementById('frmSearch').onsubmit = function() {
        window.location = 'local data here (not sure how to code this)' + document.getElementById('txtSearch').value;
        return false;
    }
</script>

        <p>



          </p>


  <form>
        <img src="" alt="Apple" style="width:100px;height:100px;">
        <p>
            </p>
        <label for="name">Apple </label>
        <label for="name">Price: $1.00 </label>

        <p>



            </p>
  <div>




      </div>


            <a [routerLink]="['BiddingPage']">Click here to bid on this item.</a>
          <p>



          </p>


  <form>
        <img src="" alt="Apple" style="width:100px;height:100px;">
        <p>
            </p>
        <label for="name">Car </label>
        <label for="name">Price: $23,560.99 </label>

        <p>



            </p>
             <a [routerLink]="['BiddingPage']">Click here to bid on this item.</a>

            <p>




                </p>

      <button>Click here to return to the top.</button>











<!-- 
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

Full code of SearchDisplay.component.ts

import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {Hero} from './hero';
import {HeroService} from './hero.service';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {HeroesComponent} from './heroes.component';
import {HeroDetailComponent} from './hero-detail.component';
import {DashboardComponent} from './dashboard.component';
import {SpreadSheetComponent} from './spreadsheeteditall.component';
import {SwitchUsersComponent} from './SwitchUsers.component';
import {BiddingPageComponent} from './BiddingPage.component';



@Component({
  selector: 'SearchAndDisplayComponent',
  templateUrl: 'app/SearchDisplay.component.html',
  styleUrls: ['app/SearchDisplay.component.css'],
  providers: [HeroService],
  directives: [ROUTER_DIRECTIVES]
})



export class SearchAndDisplayComponent{
   typeChecker(){
   var priceChecker = document.getElementById('price').nodeValue.valueOf;
   console.log(priceChecker);
   if(isNaN(+priceChecker))
   {
      alert("Entered Price is not a number, please enter a number");
   }
   var data[] = {"Apple, Car"};
   SearchBarFunction()
   {
     //not sure how to display the data
     console.log(data);
   }

   }
   GoToBiddingWebpage()
   {
    //not sure if this code is correct
    return "http://localhost:3000/SearchDisplay/BiddingPage";
   }
/*
retry()
{
  let ticks$ = Observable.interval(5000);
let responses$= XMLHttpRequest.get('somebadconnection.json')
  .retry(3)
  .map(res => res.json());

  let responses =
    ticks$
      .flatMapLatest(() => XMLHttpRequest.get('stock.sjon'))
       .map(res => res.json());

   let stockPoller = responses$.subscribe(res => console.log(res));


responses$.subscrbie(
  res => console.log(res),
  err => console.log('couldnt connect!'));

  stockPoller.unsubscribe();

}
*/
   heroes: Hero[];
  selectedHero: Hero;

  myFunction() {

}


  constructor(private _heroService: HeroService, private _router: Router) { }

  getHeroes() {
    this._heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

  gotoDetail() {
    this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]);
  }

  ngOnInit() {
    this.getHeroes();
  }

  onSelect(hero: Hero) { this.selectedHero = hero; }
}

解决方案

Try this:

<input class="search1" type="submit" name="submition" value="Search" style=" padding-  
bottom:20px; left: 691px; top: 153px; height: 23px" (click)="clicked()" />

And in your class:

...
clicked() {
     window.location.href = 'local data here (not sure how to code this)' + document.getElementById('txtSearch').value;
     return false;
}
...

Although i would think you need to make an ajax call to grab the results (or maybe top 5) from the server? If so, you'll need to use angular2 injection:

...
import {HTTP_PROVIDERS, Http} from '@angular/http';
...
@Component({
    ...
    providers: [HTTP_PROVIDERS]
    ...
})
export class test {
    ...
    constructor(private http: Http) {}
    ...
    clicked() {
        this.http.get('server address to return a json result', (data) => {
            //do something with data. you probably need to bind to another array property which is bound to the list result.
        });
        return false;
    }
    ...
}

这篇关于隐藏未输入到结果中的搜索栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆