与字符串匹配的Javascript搜索

时间:2015-11-07 10:08:36

标签: javascript jquery

我需要在fruits数组中搜索与确切字符位置匹配的内容。

var fruits = ["Apple", "Orange", "Grapes", "Banana", "Guava", "Apricot", "Avocado", "Cherry", "Water Melon"];

如果我输入 a ,则会过滤包含 a 的所有水果名称。我需要以 a 开头的水果名称。



var fruits = ["Apple", "Orange", "Grapes", "Banana", "Guava", "Apricot", "Avocado", "Cherry", "Water Melon"];

$(document).ready(function () {
    row = '';
    i = 1;
    $.each(fruits, function (key, fruit) {
        row = row + "<tr><td>" + i + "</td><td>" + fruit + "</td></tr>"
        i++;
    })
    $("table tbody").append(row);
})

$(".search").keyup(function () {
    $("table tbody tr").each(function () {
        if ($(this).find("td:eq(1)").text().toUpperCase().indexOf($(".search").val().toUpperCase()) != -1) {
            $(this).show();
        } else {
            $(this).hide();
        }
    })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="search">
<table>
    <tbody>
    </tbody>
</table>
&#13;
&#13;
&#13;

fiddle

2 个答案:

答案 0 :(得分:1)

更改此行,

    if($(this).find("td:eq(1)").text().toUpperCase().indexOf($(".search").val().toUpperCase())!=-1)

这一行

if($(this).find("td:eq(1)").text().toUpperCase().indexOf($(".search").val().toUpperCase())==0)

它应该有效

答案 1 :(得分:0)

试试这个例子

integer :: provided, rank, ierr

call MPI_INIT_THREAD(MPI_THREAD_FUNNELED, provided, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr)

if (mod(rank, 10) == 0) then
   call omp_set_num_threads(N)
else
   call omp_set_num_threads(1)
end if
var fruits = ["Apple", "Orange", "Grapes", "Banana", "Guava", "Apricot", "Avocado", "Cherry", "Water Melon"];

$(document).ready(function () {
    row = '';
    i = 1;
    $.each(fruits, function (key, fruit) {
        row = row + "<tr><td>" + i + "</td><td>" + fruit + "</td></tr>"
        i++;
    })
    $("table tbody").append(row);
})

$(".search").keyup(function () {
    $("table tbody tr").each(function () {
        if ($(this).find("td:eq(1)").text().toUpperCase().indexOf($(".search").val().toUpperCase()) == 0) {
            $(this).show();
        } else {
            $(this).hide();
        }
    })
})

JsFiddle