简体   繁体   中英

Creating a clickable search result from a JSON table

I have created a key up search function using html,ajax and JSON, and this works fine, it pulls results from the JSON table and displays them.

However, I need a user to be able to click on the search result and proceed to that relevant page. To be more specific, I am making an ecommerce page, the search brings back products for sale. So i need a user to be able to click into the product for sale. The html is below:

<div id="searcharea">
  <label for="search">
    <a href="#"><img src="images/search.jpg"></a> 
  </label>
  <input type="search" name="search" id="search" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Search';}" />
</div>
<div id="update"></div>

next is the script code:

<script>
    $('#search').keyup(function(){
        var searchField = $('#search').val();
        var myExp = new RegExp(searchField, 'i');
        $.getJSON('searchshop.json', function(data){
        var output = '<ul href class="searchresult">';
        $.each(data, function(key, val){
            if((val.brand.search(myExp) != -1) || (val.type.search(myExp) != -1)) {
                output +='<h1>' + val.brand + '</h1>';
                output +='<h2>' + val.product + '</h2>';
                output +='<img src="images/' + val.imageref +'" />';
                output +='<p>' + val.price +  '</p>';

            }
        });
            output += '</ul>';
            $('#update').html(output);
        });
    }); 
    </script>

Someone please help!

由于您已经有显示产品的代码,您可以更改它以便显示由<a>标签包装,并将href设置为相关页面(我想这是数据库的一部分,或者可以是以编程方式生成)。

In your script you can add some markup to generate links, or make the "item" container clickable.

Example making product name clickable

$.each(data, function(key, val){
    if((val.brand.search(myExp) != -1) || (val.type.search(myExp) != -1)) {
        output +='<h1>' + val.brand + '</h1>';
        output +='<h2><a href=\"link-to-product\" >' + val.product + '</a></h2>';
        output +='<img src="images/' + val.imageref +'" />';
        output +='<p>' + val.price +  '</p>';

    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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