简体   繁体   English

在Jquery .filter()函数内更改变量值

[英]Change a variable value inside a Jquery .filter() function

I have a table which has id 'myTable'. 我有一个ID为“ myTable”的表。 Now there is a textbox in which I write down the item name to find whether it exists in the myTable cell or not. 现在有一个文本框,我在其中写下项目名称以查找myTable单元格中是否存在。 To do this I have written the following code - 为此,我编写了以下代码-

var retval=0;   
var search = $("#searchitem").val().trim();
$("table#myTable tr td").filter(function() {
    if($(this).text() == search){retval=1;alert('Same item found');}
else{retval=0;}
});

The problem is that, when it finds the same item in the table cell it shows the alertbox. 问题是,当它在表单元格中找到相同的项目时,将显示警报框。 But the value of my variable retval never changes. 但是变量retval的值永远不变。 It always shows 0 . 它始终显示为0 How can I solve it? 我该如何解决?

I think what you are trying to accomplish could be done by using :contains() selector, like this: 我认为您可以通过使用:contains()选择器来完成您要完成的任务,如下所示:

var search = $("#searchitem").val().trim();
var retval = $("table#myTable tr td:contains('"+search+"'") ? 1 : 0;

I haven't tested it but I'm almost sure it works. 我还没有测试过,但是我几乎可以肯定它可以工作。 It's a much more cleaner approach and surely more readable. 这是一种更清洁的方法,而且肯定更具可读性。

jQuery :contains() docs: http://api.jquery.com/contains-selector/ jQuery:contains()文件: http : //api.jquery.com/contains-selector/

please try return false like this 请尝试像这样return false

var retval=0;   
var search = $("#searchitem").val().trim();
$("table#myTable tr td").filter(function() {
    if($(this).text() == search){
        retval=1;
        alert('Same item found');
        return false;
    }else{
        retval=0;
    }
});

change the variable value only if found , because you assign the variable to 0 at the beginning. 仅在找到时才更改变量值,因为在开始时将变量分配为0

var retval=0;   
var search = $("#searchitem").val().trim();
$("table#myTable tr td").filter(function() {
    if($(this).text() == search){
        retval=1;
        alert('Same item found');
    }
});

Try this code 试试这个代码

var search = $("#searchitem").val().trim();
var filteredData = $("table#myTable tr td").filter(function(element, index) 
{
    return $(element).text() == search;
});

now this code return array of TD elements which satisfy the condition. 现在,此代码返回满足条件的TD元素数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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