javascript - 需要表格来填充搜索栏的搜索结果

标签 javascript python html css simplehttpserver

我有一个带有搜索栏和一堆下拉菜单的网页,但现在只有搜索栏很重要。无论如何,我让它工作,当我单击搜索栏后的“转到”按钮时,它会弹出一个表格,但不会像我想象的那样将搜索到的元素放入表格中。我通过 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: $('#submit').click(函数(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>

最佳答案

您的“搜索”超出了范围。它仅存在于 .click() 的匿名函数中。您以某种方式需要将“搜索”传递到 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});
}

super 干净。但您必须花一些时间阅读 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>");

因此,从字面上写出将注入(inject)到输出中的 HTML 字符串,并将搜索结果连接到其中。不是 super 干净,但如果你只做一次,就可以完成工作。

关于javascript - 需要表格来填充搜索栏的搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31611810/

相关文章:

python - 从 UTC 偏移获取时区缩写

php - 为每个文件创建上传状态 JQuery 和 AJAX

javascript - 正则表达式将文本与第一次出现的分隔符相匹配

javascript - jQuery - 逐渐显示 div

python - 如何像使用 R hist 函数一样使用 Python 制作直方图

python - 使用 python odeint scipy 求解一系列 ode 时分割状态向量

javascript - 当img标签进入js对象时如何从javascript中的图像中提取src

javascript - Backbone.js:查看状态和路由

asp.net - 在 div 标签内右对齐菜单控件

html - 为什么旋转的图像在 css 表格中显示不同?