简体   繁体   中英

Unable to run javascript onClick in HTML?

I am trying to send the user input received through a text box and then send that input to a javascript, which is an another file (myfile.js). For some reason the html part is not working. Here is the code: myfile.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;
}

search.html

<!DOCTYPE html>
<HTML>
<HEAD>
</head>
<title>Search</title>
<body>
<script src="myfile.js" type="text/javascript"></script>
<form name="input">

Search for: <input type="text" id ="keytex" name="keytext" onClick='if(document.getElementById("keytex").value!=\'\') findString(document.getElementById("keytex").value); return(false);'>
</form>
<p> You can search this text. Search the text again</p>
</body>
</html>

Um... Did you even check your HTML? (There are many errors in your code, here's one.)

<input onClick='if(document.getElementById("keytex").value!=\'\') findString(document.getElementById("keytex").value); return(false);'>

See those \\' ? You can not do that in HTML. Plus, use brackets if(){} in inline codes.

This should works:

if(document.getElementById("keytex").value!="")

PS: Don't use inline JavaScript. They will only give you a messier HTML at the end.

//Good
document.querySelector("#keytex").addEventListener("click",function(){
    if(this.value!=""){             //Use "this" to refer back the element.
        findString(this.value);
    }
    return false;
});

Learn more about:

可能您想使用onchange或onkeyup事件-不是onclick

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