0

我试图显示和隐藏 div 内容取决于用户的输入。

这是我的代码:

<input type="text" name="pass" id="pass" onkeyup="check_input(this.value)">

<div id="repeated_pattern" style="display:none">
    <b>REPEATED PATTERN</b>
    <p>Repeated characters</p>
</div>

<script>
function check_input(value){
     //this would check if there are 3 or more characters repeated consecutively
     var repeat_pattern = /(.)\1\1/.test(value);  

     if(repeat_pattern)  { 
        $("#repeated_pattern").show(500); 
     }else{ 
        $("#repeated_pattern").hide(500); 
     }
}    
</script>

测试:

  1. 当我尝试输入gg时,没有显示 div 内容,所以结果还可以
  2. 当我尝试输入ggg时,会显示 div 内容,所以结果还可以
  3. 但是当我尝试删除它时g,它就是现在gg。它应该是 div 内容必须隐藏但仍然显示。onkeyup无法正常使用该hide()功能。

如何使用 hide() onkeyup 工作,反之亦然?

4

1 回答 1

1

我收到此错误:

ReferenceError: check_input is not defined

尝试在 Javascript 中设置事件处理程序,使其在范围内:

http://jsfiddle.net/vHREF/1/

Javascript:

// Event handlers
if(document.addEventListener)
document.getElementById('pass').addEventListener('keyup',check_input,false);
// Good old Internet Explorer event handling code
if(document.attachEvent)
document.getElementById('pass').attachEvent('keyup',check_input);

function check_input() {
    var value = $(this).val();
    //this would check if there are 3 or more characters repeated consecutively
    var repeat_pattern = /(.)\1\1/.test(value);

    if (repeat_pattern) {
        $("#repeated_pattern").show(500);
    } else {
        $("#repeated_pattern").hide(500);
    }
}

HTML:

I'm trying to show and hide div contents depends on the input of the user. Here are my codes:
<input type="text" name="pass" id="pass">
<div id="repeated_pattern" style="display:none"> <b>REPEATED PATTERN</b>

    <p>Repeated characters</p>
</div>
于 2013-03-29T03:22:04.680 回答