简体   繁体   English

Javascript附加输入字段

[英]Javascript appending input fields

I have this script JsFiddle and I am trying to change submitted characters, but when you press for ex: s twice as in ss instead of showing xx it changes it to ss 我有这个脚本JsFiddle,并且我尝试更改提交的字符,但是当您按ex键时: sss s两倍,而不是显示xx它将其更改为ss

Full code: 完整代码:

<body>
    <div id='out'></div>

    <textarea id="in" name="messages" onkeyup="test()"></textarea>
    <input type="submit" id="submit" name="submit" />

Js function: js功能:

    function test(){            
        var origin = document.getElementById("in").value;
        var send = document.getElementById("out"); 

       if(origin =='s'){
        origin = 'z';
       }
        send.innerHTML = origin;
    }

    </script>
var replacements = {
    "s": "z",
    // repeat for all the characters you want to replace
};

var neworigin = '';
for (var i = 0; i < origin.length; i++) {
    neworigin += (origin[i] in replacements) ? replacements[origin[i]] : origin[i];
    }
}
send.innerHTML = neworigin;

It looks like you want to replace all s characters with z before assigning to send . 似乎您要在分配send之前用z替换所有s字符。 Your current code only replaces s with z if origin is exactly one s . 您当前的代码只替换sz如果origin恰好是一个s Try this instead: 尝试以下方法:

send.innerTHML = origin.replace(/s/g, 'z');

That will replace every occurrence of s with z in origin and assign the result to send.innerHTML . 它将在origin中用z替换每次出现的s并将结果分配给send.innerHTML (In case it isn't obvious, with this you can get rid of the if statement.) (以防万一,您可以摆脱if语句。)

If you want to replace all characters with the same substitute character, you can change the regex from /s/g to /./g . 如果要用相同的替换字符替换所有字符,可以将正则表达式从/s/g更改为/./g If you want to replace each character with something else that depends on the character, you can use a look-up function: 如果要用其他取决于字符的字符替换每个字符,则可以使用查找功能:

var mapper = function(match) {
    return match === 's' ? 'z' : '?'; // or whatever mapping function you want
}
send.innerHTML = origin.replace(/./g, mapper);

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

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