简体   繁体   中英

How to call JS function

I don't know how to rewrite this code. I have simple code which contains JS code in html code ( onkeydown event).

I want put JS code to extern JS file and only call method. But i don't know how. Can you tell me how?

Code is:

<textarea onkeydown="if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;return false;}">
</textarea>

Thank you.

<script>
// in a new js-file
function onKeyDown(event) {
      if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;
      return false;}
}

var textarea = document.getElementById('textarea');
textarea.addEventListener('keydown', onKeyDown.bind(textarea));
</script>

<textarea id="textarea"></textarea>    

Well you can create a file myscripts.js with

<script>
    function myFunc(event) {
        if(event.keyCode===9){
            var v=this.value,s=this.selectionStart,e=this.selectionEnd;
            this.value=v.substring(0, s)+'\t'+v.substring(e);
            this.selectionStart=this.selectionEnd=s+1;
            return false;
        }
    }
<script>

And a html file with

<script src="myscripts.js"></script>
<textarea onkeydown="myFunc(event)"></textarea>

Also take a look at this link How to use keydown event in textarea?

Hope that helps.

Hum externalise your JS code.

<textarea id="mytext"></textarea>

<script>
document.getElementById("mytext").onkeydown = function(event){
   if(event.keyCode===9){
var v=this.value, s=this.selectionStart, e=this.selectionEnd; this.value=v.substring(0, s)+'\t'+v.substring(e); this.selectionStart=this.selectionEnd=s+1; 
return false;
}
//You're function here
}
</script>

HTML

 <textarea id="mytest"></textarea>

JS

document.getElementById("mytest").onkeydown = function (event){
            alert("keydown");
            if(event.keyCode===9){
                var v=this.value,
                    s=this.selectionStart,
                    e=this.selectionEnd;
                    this.value=v.substring(0, s)+'\t'+v.substrin(e);
                this.selectionStart=this.selectionEnd=s+1;      
                return false;
        }
}

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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