[英]Inline Javascript works, but doesn't work externally
I am fairly new to JavaScript and I was wondering if anyone can help me with this problem. 我对JavaScript相当陌生,我想知道是否有人可以帮助我解决这个问题。 I have three text boxes, and the first two show first and last name.
我有三个文本框,前两个显示名字和姓氏。 And I want the last textbox to contain both first and last.
我希望最后一个文本框同时包含第一个和最后一个。
Here's the code: 这是代码:
<!doctype html>
<html>
<head>
<title>Javascript Textbox</title>
</head>
<body>
First Name: <input id="fname" type="text" value="John"><br>
Last Name: <input id="lname" type="text" value="Smith"><br>
<input id="textbox" readonly>
<button onclick="textbox.value=fname.value+' '+lname.value">press to see full name</button>
<script type="text/javascript" src="testing.js"></script>
</body>
</html>
This works fine, but when I try to use an external file, testing.js
and switching onclick="testFunction()"
, it doesn't work anymore. 这可以正常工作,但是当我尝试使用外部文件
testing.js
并切换onclick="testFunction()"
,它将不再起作用。
testing.js: testing.js:
function testFunction() {
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var textb = document.getElementById("textbox").value;
textb = first + " " + last;
}
http://jsfiddle.net/1vshky4s/ http://jsfiddle.net/1vshky4s/
Ultimately your problem is that you are assigning the texb var the value of the text box, then overriding it with a concatenated string, then doing nothing at all with the results. 最终,您的问题是要为texb var分配文本框的值,然后使用串联字符串覆盖它,然后对结果完全不执行任何操作。
function testFunction()
{
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var textb = first + " " + last;
document.getElementById("textbox").value = textb;
}
actually do something with the textb var and you should be good to go. 实际使用textb var做些事情,您应该一切顺利。 Check the fiddle.
检查小提琴。
change your function to 将功能更改为
function testFunction() {
var first = document.getElementById("fname");
var last = document.getElementById("lname");
var textb = document.getElementById("textbox");
textb.value = first.value + " " + last.value;
}
Move: 移动:
<script type="text/javascript" src="testing.js"></script
Into the head
of page. 进入页面
head
。 You try to bind function, than doesn't exist. 您尝试绑定功能,但不存在。
script
will be loaded after dom. script
将在dom之后加载。
ps Or use 'onload' event if window
pss ps或如果
window
pss使用'onload'事件
Here correct function: 这里正确的功能:
function testFunction()
{
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var textb = document.getElementById("textbox"); //!
textb.value = first + " " + last; // here was error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.