需要使用搜索栏

时间:2015-07-24 13:28:23

标签: javascript python html css3 simplehttpserver

我有一个带有搜索栏和一系列下拉菜单的网页,但现在搜索栏非常重要。无论如何我有它工作的地方,当我点击搜索栏后面的go按钮它会带来一个表,但不会像我想的那样把搜索到的项目放在表中。我通过Python使用SimpleHTTPServer

<form role="form" id="form">
        <fieldset>
            <div class="form-group">
            <div class="row">
            <label for="search"> </label>
            <div class="col-lg-7 col-lg-offset-2">
            <input type="text"
                class="form-control" name="search" id="search"
                placeholder="Search for..." />
            </div>

                <div class="col-lg-2">
                <br>
                <button type="button" class="btn btn-success" id="submit">       Go!
                </button> </div> </div> </div>
            </fieldset>
    </form> 

JS:     $(&#39;#提交&#39;)。点击(函数(E){             e.preventDefault();

         var search=$('#search').val();
         $.get('post2.html', function(returndata){

         $('#output').html(returndata);

         } );


    });

<table class="table">
    <thead>
        <tr>
        <th> Previous Searches: </th>
        </tr>
    </thead>

        <tr>
        <script>document.write(search)</script>
        </tr>

</table>

1 个答案:

答案 0 :(得分:0)

您的搜索&#34;超出范围。它只存在于.click()的匿名函数中。你不知何故需要通过&#34;搜索&#34;进入您的HTML,但您当前的设置无法实现这一点。

我建议使用Handlebars之类的东西,它允许您使用可变占位符定义模板化HTML,编译它们,然后插入变量值。例如,您可以在HTML中定义:

<script type="text/x-handlebars-template" id="table-data-template">
    <table class="table">
        <thead>
            <tr>
                <th> Previous Searches: </th>
            </tr>
        </thead>

        <tr>
            {{data}}
        </tr>
    </table>
</script>

在你的JS中,你可以这样做:

$('#submit').click(function(e){ 
    e.preventDefault();
    var renderData = Handlebars.compile($("#table-data-template").html());
    var search=$('#search').val();
    $('#output').html(renderData({data: search});
}

超级干净。但是你必须花一些时间阅读Handlebars以及所有这些。

如果你没有在你的应用程序中做很多基于模板的工作,因此Handlebars可能有点矫枉过正,你可以简单地在JS中定义HTML模板:

$('#submit').click(function(e){ 
    e.preventDefault();
var search=$('#search').val();
$('#output').html(
    "<table class='table'>
        <thead>
            <tr>
                <th> Previous Searches: </th>
            </tr>
        </thead>

        <tr>" + search +     
        "</tr>
    </table>");

因此,字面上写出将在输出中注入的HTML字符串,并在那里汇总搜索结果。不是超级干净,但如果你只做一次,就完成工作。

相关问题