简体   繁体   English

在JavaScript过滤器函数中使用if else

[英]Using if else inside Javascript filter function

在此处输入图片说明 My fiddle 我的小提琴

I have this fiddle. 我有这个小提琴。 I want to use if else inside the filter function like this. 我想在过滤器功能内使用其他方式。 The one I have works but the loop doesn't seem to break. 我有一个工作,但循环似乎没有中断。 Since it doesn't break, the else part is printed for all the not filtered conditions. 由于它不会损坏,因此将为所有未过滤的条件打印else部分。 How to break this loop? 如何打破这个循环? Or any better idea for this? 还是对此有更好的主意?

I have two textboxes and a button, when I enter caption and qty and hit add, I want to check if it already exists on the table. 我有两个文本框和一个按钮,当我输入标题和数量并单击添加时,我想检查它是否已经存在于表中。 If it exists I want to replace the qty to new value. 如果存在,我想将数量替换为新值。 If it doesn't exists I want to add new row with new caption and qty. 如果不存在,我想添加带有新标题和数量的新行。 The checking of existence is mystery for me doesn't work at all. 对我来说,存在的检验是个谜,这根本行不通。

$('#btnAdd').click(function () {
        debugger;
        UOMCaption = $('#UOMCaption').val();
        UOMQty = $('#UOMQuantity').val();

        $("#tbluom tr td:first-child").filter(function () {
            if ($(this).text().indexOf(UOMCaption) > -1) {
                $(this).next("td").text("found it");
            }
            else {
                $('#tbluom >tbody').append('<tr><td>' + UOMCaption + '</td><td>' + UOMQty + '</td></tr>');
            }
        });
        $('#UOMCaption,#UOMQuantity').val("");
    });

If you want the looping to break after first match then use 如果您想在第一次比赛后中断循环,请使用

$("#tbluom tr td:first-child").each(function () {
    if ($(this).text().indexOf(UOMCaption) > -1) {
        $(this).next("td").text("found it");
        return false;
    } else {
        $('#tbluom >tbody').append('<tr><td>' + UOMCaption + '</td><td>' + UOMQty + '</td></tr>');
    }
});

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

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