[英]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). 我正在尝试通过文本框发送接收到的用户输入,然后将该输入发送到另一个文件(myfile.js)的javascript。 For some reason the html part is not working.
由于某些原因,html部分无法正常工作。 Here is the code: myfile.js:
这是代码: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 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? 嗯...您甚至检查过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. 您无法在HTML中做到这一点。 Plus, use brackets
if(){}
in inline codes. 另外, 在内联代码中使用方括号
if(){}
。
This should works: 这应该工作:
if(document.getElementById("keytex").value!="")
PS: Don't use inline JavaScript. PS:请勿使用内联JavaScript。 They will only give you a messier HTML at the end.
最后,它们只会给您一个更混乱的HTML。
//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: 学习更多关于:
this
https://developer.mozilla.org/en/JavaScript/Reference/Operators/this this
https://developer.mozilla.org/en/JavaScript/Reference/Operators/this addEventListener
- https://developer.mozilla.org/en/DOM/element.addEventListener addEventListener
- https://developer.mozilla.org/en/DOM/element.addEventListener 可能您想使用onchange或onkeyup事件-不是onclick
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.