keyup函数的Javascript问题-尝试多次使用页面上的同一表单域,但只有第一个表单域有效 [英] Javascript issue with keyup function - trying to use same form field on page multiple times but only 1st form field works

查看:102
本文介绍了keyup函数的Javascript问题-尝试多次使用页面上的同一表单域,但只有第一个表单域有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我在同一个html页面上有多个词汇表.
  2. 在每个词汇表上,我希望用户可以在字段中输入单词或短语以仅查看包含输入的单词或短语的表行.例如,如果输入"orde",则不包含字符串"orde"的表行将消失.如果您访问 http://www.amanado.com/idioma-colombiano/,单击"Vocabulario(oficial y de jerga)-palabras y frases comunes"以展开手风琴部分,然后在"Ingresa palabra o frase en el siguiente campo para filtrar lainformationaciónde"字下的字段中输入"orde"拉塔布拉".输入"orde"后,词汇表中除2行外的所有行都应消失(剩下2行).
  3. 我有2个问题.我遇到的第一个问题是我无法在页面上的每个词汇表上方重复表单字段,因为在执行此操作时,只有表单字段的第一个外观起​​作用.我遇到的第二个问题是,我希望form字段仅适用于表正下方的所有行.当前,表单字段适用于页面上具有"myTable"类的所有表的所有行.也许我可以以某种方式为每个表指定一个表ID,然后使表上方的表单字段仅适用于表字段下方的表的表ID.并且,无需添加太多的javascript或额外的CSS类(最好是避免添加更多的CSS类)来实现这一点将是很棒的.我猜想这两个问题都可以用几行javascript来解决,并且可以为每个表添加一个统一格式的表ID(例如filter1,filter2,filter3)来解决.
  4. 下面是(a)出现在我的html中的表单字段; (b)出现在我的html中的打开表格标记的示例;和(c)我正在使用的javascript.
  5. 我不是软件工程师,但是如果有人告诉我要具体做什么,我确实知道如何实施更改(例如,进行此确切的更改,然后进行此准确的更改,然后进行此准确的更改).我感谢任何人都可以提供的任何帮助,尤其感谢字面说明.
  1. I have multiple vocabulary tables on the same html page.
  2. Above each vocabulary table, I would like to enable users to enter a word or phrase in a field to view only the table rows that contain the entered word or phrase. For example, if you enter "orde", the table rows that do not contain the string "orde" will disappear. This is already working if you visit http://www.amanado.com/idioma-colombiano/, click on "Vocabulario (oficial y de jerga) - palabras y frases comunes" to expand the accordion section, and then enter "orde" in the field below the words "Ingresa palabra o frase en el siguiente campo para filtrar la información de la tabla". After entering "orde", all but 2 rows in the vocabulary table should disappear (2 rows remain).
  3. I am having 2 issues. The 1st issue I am having is that I am unable to repeat the form field above each vocabulary table on the page because only the 1st appearance of the form field is functional when I do this. The 2nd issue I am having is that I would like the form field to apply only to all rows of the table directly below it. Currently the form field applies to all rows of all tables on the page that have a class of "myTable". Perhaps I could somehow specify a table id for each table and then have the form field above the table only apply to the table id of the table directly below the form field. And, it would be great to achieve this without having to add too much more javascript or additional css classes (preferably, I would like to avoid adding more css classes). I am guessing that both of these issues can be resolved with a couple additional lines of javascript and possibly the addition of a table id for each table in a consistent format (e.g., filter1, filter2, filter3).
  4. Below are (a) the form field as it appears in my html; (b) an example of an open table tag as it appears in my html; and (c) the javascript I am using.
  5. I am not a software engineer, but I do know how to implement a change if someone tells me what to do specifically (e.g., make this exact change, then make this exact change, then make this exact change). I appreciate any assistance anyone can provide and literal instructions would be especially appreciated.

(a)表单字段从此处开始

<form class="live-search" action="" method="post">
<p>Ingresa palabra o frase en el siguiente campo para filtrar la información de la tabla</p>
<input id="filter" class="text-input" type="text" value="Mostrar sólo filas que contengan..." onFocus="clearText(this)" onBlur="clearText(this)" />
</form>

(a)表单字段在此处结束

(b)打开表格标记从此处开始

<table class="myTable" summary="Palabras y frases (oficiales y de jerga)">

(b)打开表格标记在此处结束

(c)javascript从此处开始(来源:

(c) javascript starts here (source: http://www.designchemical.com/blog/index.php/jquery/live-text-search-function-using-jquery/; I made 1 modification to this javascript to make it only apply to rows of tables w/ class="myTable")

$(document).ready(function(){
$("#filter").keyup(function(){

// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;

// Loop through the comment list
$('table[class="myTable"] tr').each(function(){

// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();

// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});

// Update the count
var numberItems = count;
$("#filter-count").text(" Total = "+count);
});
});

(c)javascript到此结束

从这里开始对甜菜根建议的变化进行分析

ANALYSIS OF BEETROOT SUGGESTED CHANGES STARTS HERE

甜菜根,谢谢.我实施了您建议的更改.结果,我发现了4个小错误,与您已经解决的错误相比,它们都容易解决. #1和#2是排行榜,而#3和#4是我可以管理的.如果您或其他人可以指导我如何消除以下#1和#2的错误,那就太好了.我非常感谢您已经提供的慷慨帮助.

Beetroot, thank you. I implemented your suggested changes. As a result, I found 4 small bugs, which I believe are all a lot easier to solve than what you already solved. #1 and #2 are showstoppers and #3 and #4 I manageable. If you or someone else can instruct me how to eliminate the bugs for #1 and #2 below, that would be excellent. I very much appreciate the gracious help you've already provided.

1):找到1或匹配项时,过滤器计数正确.但是,清除输入字段后,将显示表行的总数,并且该数目不正确.显示的数字是"1"到高.例如,转到该问题顶部#2中提供的同一Amanado.com链接(Stackoverflow不允许我向该问题添加另一个链接b/c我是新用户),展开"Vocabulario (oficial y de jerga)-abreviaturas comunes手风琴,在输入字段"Ingresa palabra o frase en el siguiente campo para filtrar lainformationaciónde la tabla"下方的输入字段中输入"ap",结果为"2"行,其中是正确的.然后,通过删除"ap"来清除输入字段,结果是"19"行,这是不正确的(此表的正确行数是"18".也许标头行被计为一行,我猜正在计数的标题行可能是个问题,因为标题行消失时计数是正确的,尽管标题行永不消失(每个问题/下面的错误2),请注意,我做了1次更改对Beetroot的建议更改,即出于外观/美观原因,我将$ count.text("Total =" + count)更改为((" + count +)"),我希望这与此错误的过滤器无关计数问题.

1) When 1 or matches is found, the filter-count is correct. However, after clearing the input field, the total number of table rows is displayed and this number is incorrect. The number displayed is "1" to high. For example, go to the same Amanado.com link provided in #2 at the top of this question (Stackoverflow doesn't allow me to add another link to this question b/c I'm a new user), expand the "Vocabulario (oficial y de jerga) - abreviaturas comunes" accordion, enter "ap" in the input field below the words "Ingresa palabra o frase en el siguiente campo para filtrar la información de la tabla" and the result is "2" rows, which is correct. Then clear the input field by deleting the "ap" and the result is "19" rows, which is incorrect (the correct # of rows is "18" for this table. Perhaps the header row is being counted as a row, which it should not be. I am guessing the header row being counted may be the issue because the count is correct when the header row disappears, although the header row should never disappear (per issue/bug #2 below). Note that I made 1 change to Beetroot's suggested changes, which was that I changed $count.text(" Total = " + count) to ("(" + count + ")") for appearance/aesthetic reasons. I hope this has no relationship to this incorrect filter-count issue.

2)在输入字段中输入值时,表标题行会丢失.但是,表标题行应始终可见.请注意,根据上面的#1,当表头行消失时,行数是正确的;而在表头行存在时,行数是不正确的("1"太多).

2) When a value is entered in an input field, the table header row is lost. However, the table header row should always be visible. Note per #1 above that when the table header row disappears, the row count is correct, and when the table header row is present, the row count is incorrect ("1" too many).

3):删除标签后,输入字段的css丢失/不正确.以下是我正在使用的CSS.我尝试在javascript中将"input-text"替换为"live-search",并在输入字段中将class ="input-text"更改为"live-search",但这并没有恢复CSS,因此我消除了这些更改然后返回您所提供的javascript和输入字段.因此,到目前为止,我仍然拥有多余的标签,因为在删除标签时,我没有成功地使css正常工作.

3) When the tag is removed, the css is lost/incorrect for the input field. Below is the css I am using. I tried replacing "input-text" with "live-search" in the javascript and changing class="input-text" to "live-search" in the input field, but this did not restore the css, so I eliminated these changes and returned to the javascript and input field as you provided. So, for now, I continue to have the extraneous tag because I haven't been successful getting the css to work when the tag is removed.

4)当以下标记中出现"0"时,页面上至少出现第一个输入字段时显示"0".但是,如果未输入任何内容,则不应出现"0".如果未输入任何内容时显示"0",则"0"是不正确的/误导性的,因为所有表行均可见,并且正确的过滤器计数应为表头行的可见表行总数减去"1".为了解决此问题,我从中删除了"0",这消除了当表行可见时的"0"外观,并且这似乎没有引起任何新的问题.

4) When "0" is present in the following tag, the "0" appears on the page for at least the 1st appearance of the input field. However, "0" should not be present when nothing has been entered. If "0" is present when nothing has been entered, "0" is incorrect/misleading because all table rows are visible and the correct filter-count should be the total of the visible table rows minus "1" for the table header row. To address this issue, I removed the "0" from the , this eliminated the appearance of the "0" when table rows are visible, and this does not seem to have caused any new issue.

Changed from:   <span class="filter-count">0</span>
Changed to:     <span class="filter-count"></span>

5)以下是在完成Beetroot建议的更改后我正在使用的当前(a)输入字段,(b)表打开标记,(c)css和(d)javascript .

5) Below is the current (a) input field, (b) table open tag, (c) css, and (d) javascript that I am using after making the changes that Beetroot suggested.

(a)输入字段从此处开始

<form class="live-search" action="" method="post">
<p>Ingresa palabra o frase en el siguiente campo para    filtrar la información de la tabla</p>
<input class="input-text" type="text" value="Mostrar sólo    filas que contengan..." />
<span class="filter-count"></span>
</form>

(a)输入字段在此处结束

(b)表格打开标记从此处开始

<table class="myTable" summary="Palabras y frases (oficiales y de jerga)">

(b)表打开标记在此处结束

(c)css从这里开始

.live-search {
overflow: hidden; 
width: 100%; 
padding: 8px 0; 
border: 0px solid #e3e3e3; 
margin-bottom: 10px;
font-size: 12px;
color: rgb(61, 61, 61) !important;
}

.live-search input {
border:1px solid #ddd;
padding:5px 8px;
width:300px; 
font-size: 12px;
color: rgb(61, 61, 61) !important;
-moz-border-radius:4px;
-webkit-border-radius:4px;
}

.live-search input:focus {
border-color: #c3c3c3;
-moz-box-shadow: 0 0 3px rgba(0,0,0,.2);
-webkit-box-shadow: 0 0 3px rgba(0,0,0,.2);
box-shadow: 0 0 3px rgba(0,0,0,.2);     
}

(c)CSS到此结束

(d)javascript从此处开始

$(function() {
$(".input-text").keyup(function() {
var $this = $(this),
count = 0,
pattern = new RegExp($this.val(), "i"),
$group = $this.closest(".group"),
$count = $group.find(".filter-count");
$group.find(".myTable tr").each(function() {
$tr = $(this);
if ($tr.text().search(pattern) < 0) {
$tr.fadeOut();
} else {
$tr.show();
count++;
}
$count.text("(" + count + ")")
});
}).on('focus blur', function() {
if (this.defaultValue == this.value) this.value = '';
else if (this.value == '') this.value = this.defaultValue;
});
});

(d)javascript到此结束

推荐答案

此处的窍门是相对于当前正在接收文本的输入元素起作用.

The trick here is to work relative to the input element which is currently receiving text.

说明:

  • 修改文本输入字段以读取<input class="text-input" type="text" value="Mostrar sólo filas que contengan..." />并添加到所有其他相关组.除非将表单用于其他用途,否则这些字段无需包装在<form></form>标记中.
  • <span class="filter-count">0</span>(或类似名称)添加到所有相关组.此元素将接收count统计信息.
  • 删除功能clearText.
  • 将javascript修改如下:
  • Modify the text input field to read <input class="text-input" type="text" value="Mostrar sólo filas que contengan..." /> and add to all other relevant groups. These fields do not need to be wrapped in <form></form> tags unless the form is used for something else.
  • Add <span class="filter-count">0</span> (or similar) to all relevant groups. This element will receive the count statistic.
  • Delete the function clearText.
  • Modify the javascript to read as follows :

:

$(function() {
    $(".text-input").keyup(function() {
        var $this = $(this),
            count = 0,
            pattern = new RegExp($this.val(), "i"),
            $group = $this.closest(".group"),
            $count = $group.find(".filter-count");
        $group.find(".myTable tr").each(function() {
            $tr = $(this);
            if ($tr.text().search(pattern) < 0) {
                $tr.fadeOut();
            } else {
                $tr.show();
                count++;
            }
        });
        $count.text(" Total = " + count);
    }).on('focus blur', function() {
        if (this.defaultValue == this.value) this.value = '';
        else if (this.value == '') this.value = this.defaultValue;
    });
});

未经测试,因此可能需要调试.工作时,它应该比当前代码快很多.

Untested, so may need debugging. When it's working it should be a lot faster than the current code.

这是一个新版本,可修复以前的错误并进一步提高性能.

Here's a new version which fixes previous bugs and further enhances performance.

$(function() {
    $(".text-input").on('keyup', function(e) {
        var disallow = [37, 38, 39, 40];//ignore arrow keys
        if($.inArray(e.which, disallow) > -1) {
            return true;
        }
        var inputField = this,
            val = this.value,
            pattern = new RegExp(val, "i"),
            $group = $(this).closest(".group"),
            $trs = $group.find(".myTable tbody tr"),
            $s;
        if(val === '') {
            $s = $trs;
        }
        else {
            $s = $();
            $trs.stop(true,true).each(function(i, tr) {
                if(val !== inputField.value) {//if user has made another keystroke
                    return false;//break out of .each() and hence out of the event handler
                }
                $tr = $(tr);
                if ($tr.text().match(pattern)) {
                    $s = $s.add(tr);
                }
            });
            //$trs.not($s).fadeOut();
            $trs.not($s).hide();
        }
        $group.find(".filter-count").text("(" + $s.show().length + ")");
    }).on('focus blur', function() {
        if (this.defaultValue == this.value) this.value = '';
        else if (this.value == '') this.value = this.defaultValue;
    });

    $(".group").each(function() {
        $this = $(this);
        $this.find(".filter-count").text("(" + $this.find("tbody tr").length + ")");
    });
});

您可以尝试.fadeOut(),但我个人更喜欢使用.hide().

You can try .fadeOut() but I personally prefer it with .hide().

这篇关于keyup函数的Javascript问题-尝试多次使用页面上的同一表单域,但只有第一个表单域有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆