Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据条件将文本从一个文本框复制到另一个文本框_Javascript_Json_Textbox_Conditional Statements - Fatal编程技术网

Javascript 根据条件将文本从一个文本框复制到另一个文本框

Javascript 根据条件将文本从一个文本框复制到另一个文本框,javascript,json,textbox,conditional-statements,Javascript,Json,Textbox,Conditional Statements,我正在研究javascript 分别考虑两个文本框tb1和tb2 tb1中存在的值应根据条件复制到tb2中。如果条件为真,则无需复制任何内容。如果条件为假,tb1中的值也应初始化为tb2。是的,这是可能的。你需要定义你想要它发生的时间。在第一个文本框的onkeypress或onblur中,您可以调用一个函数来验证您的条件,然后复制值 tb1.onblur(function(){ if(condition) tb2.value = tb1.value } 上面的代码不起作用,它只是一个伪代码。

我正在研究javascript

分别考虑两个文本框tb1和tb2


tb1中存在的值应根据条件复制到tb2中。如果条件为真,则无需复制任何内容。如果条件为假,tb1中的值也应初始化为tb2。是的,这是可能的。你需要定义你想要它发生的时间。在第一个文本框的onkeypress或onblur中,您可以调用一个函数来验证您的条件,然后复制值

tb1.onblur(function(){ if(condition) tb2.value = tb1.value }
上面的代码不起作用,它只是一个伪代码。


<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
    <div>
        <span>tb1:</span>
        <input id="tb1" type="text" value="TextBox Value 1"/>
    </div>
    <div>
        <span>tb2:</span>
        <input id="tb2" type="text" value="TextBox Value 2"/>
    </div>
    <input type="button" onclick="exchange()" value="Exchange">
    <script type="text/javascript">
        function exchange(){
            var tb1 = document.getElementById('tb1');
            var tb2 = document.getElementById('tb2');
            var condition = function(){
                return true;
            };

            if(condition()){
                var buf = tb1.value;
                tb1.value = tb2.value;
                tb2.value = buf;
            }
        }
    </script>
</body>
</html>
tb1: tb2: 函数交换(){ var tb1=document.getElementById('tb1'); var tb2=document.getElementById('tb2'); var条件=函数(){ 返回true; }; if(条件()){ var buf=tb1.0值; tb1.value=tb2.value; tb2.1值=buf; } }
这里有一个函数可以满足您的需要:

function compareAndCopy() {
    var tb1 = document.getElementById("tb1");
    var tb2 = document.getElementById("tb2");

    if (tb1.value == "hey") {
        tb2.value = tb1.value;
    } else {
        alert("No match");
    }
}

//Add a handler
document.getElementById("tb1").onblur = compareAndCopy;
它当前正在检查模糊上的
tb1
是否等于
hey


工作演示:

很有可能……你什么时候在blur上进行每次按键比较?