我需要在document.write
内调用一个变量,但它不起作用......
示例
function(){
var variable=document.getElementById("text");
alert("your text "+ variable);
}
表内有:
document.write('<td><input type="text" id="example"></td>');<br>
document.write('<td><input type="button" value="enter a text" onclick="function()">
答案 0 :(得分:2)
javascript中允许使用下面的匿名函数,但我们无法在以后使用元素等中的function(){}
来调用它们。他们需要有一个参考,在您的情况下,只需function
之后的名称
function(){
//Your code
}
变为
function myFunction(){ //myFunction can be changed to another more suitable name
//Your code here;
}
然后从document.write
语句中调用onclick
事件中的命名函数
document.write('<td><input type="text" id="example"></td>');<br>
document.write('<td><input type="button" value="enter a text" onclick="myFunction()">
既然您没有使用function()
这是javascript中的保留字,但使用myFunction()
javascript现在认为是您的命名函数,它应该可以正常工作
答案 1 :(得分:1)
function
是保留关键字,您不能将其用作函数名称。
答案 2 :(得分:1)
var newFunction = function(){
var variable=document.getElementById("text");
alert("your text "+ variable);
}
document.write('<td><input type="button" value="enter a text" onclick="newFunction()">
答案 3 :(得分:0)
您需要引用要阅读的Element的哪个属性。简单地使用getElementById将返回对象,而不是textfield的值。使用getelementById('text').value
。
答案 4 :(得分:0)
不确定您的代码中有多少是真实的,而且只是一个示例,但是您需要仔细检查getElementById()
并检查您提供的ID实际上是否在HTML中。
在您的示例中,您展示了getElementById("text")
但是没有任何ID为text
的HTML
此外,如果要提取存储在该变量中的内容,您可能希望通过getElementById("text").value
但主要问题似乎是您正在使用function(){}
- 您应该为您的功能命名,例如:function foo(){}
然后使用onclick='foo()'
来调用它。
答案 5 :(得分:0)
function
是保留关键字。
您可以像这样使用
var func = function(){
var variable=document.getElementById("text");
alert("your text "+ variable);
}
onclick="func()"