简体   繁体   English

如何将变量从html表单传递到.js文件?

[英]How to pass a variable from a html form to a .js file?

Here is my code 这是我的代码

File external.js: 文件external.js:

var TRange=null;

function findString (str) {
 if (parseInt(navigator.appVersion)<4) return;
 var strFound;
 if (window.find) {

  // CODE FOR BROWSERS THAT SUPPORT window.find

  strFound=self.find(str);
  if (!strFound) {
   strFound=self.find(str,0,1);
   while (self.find(str,0,1)) continue;
  }
 }
 else if (navigator.appName.indexOf("Microsoft")!=-1) {

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
 }
 else if (navigator.appName=="Opera") {
  alert ("Opera browsers not supported, sorry...")
  return;
 }
 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}

File Search.html: 文件Search.html:

<html>
<head></head>
<title>Search</title>
<body>
<form name="input" action = "external.js">
Search for: <input type="text" name="keytext" /><br />
</form>
<p> You can search this text. Search the text again</p>
</body>
</html>

I am looking for a method to modify the form part of the HTML file such that it can make a call to the external JavaScript (external.js) and pass the parameters. 我正在寻找一种方法来修改HTML文件的表单部分,以便它可以调用外部JavaScript(external.js)并传递参数。 The parameter will be the text in the input box. 该参数将是输入框中的文本。

in your search.html add a reference to the javascript file. 在您的search.html中添加对javascript文件的引用。 like so 像这样

<script src="external.js" type="text/javascript"></script>

you can then call functions within the javascript file like so 然后你可以像这样在javascript文件中调用函数

<input type="text" name="keytext" onClick='findString("test")'/>

in this example you'd be passing the string "test" to your function findString 在这个例子中,你将字符串“test”传递给你的函数findString

Edit: you can use other events like onblur as well, it all depends when you want to fire the event. 编辑:您也可以使用其他事件,如onblur ,这一切都取决于您何时要触发事件。

Hope this helps. 希望这可以帮助。

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

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