2017-04-16 84 views
1

首先,我知道这个问题之前已经被问过 - 我看过这些答案,但由于某种原因,它根本不适合我!使用Javascript和HTML创建一个清晰的按钮

我有各种各样的,我想有一个“清除”按钮,点击时清空字段的值文本字段。

这是我的JavaScript:

function clear() { 
    document.getElementById("customerName").value=""; 
} 

和我因为这是HTML ...

<table border="1" id="orderForm"> 
    <tr> 
     <th colspan="2">Customer Details</th> 
    </tr> 
    <tr> 
     <td id="font">Customer Name</td> 
     <td><input type="text" id="customerName"></td> 
    </tr> 
</table> 

<button type="button" id="button1" onClick="clear()">Clear</button> 

我不知道为什么它不会工作,我一直在努力让它工作多年。

+0

试着改变你的函数名。 选中此项[是否清除Javascript中的保留字?](http://stackoverflow.com/questions/7165570/is-clear-a-reserved-word-in-javascript) – Pratyush

+0

这是正确的!简直不敢相信那么简单。非常感谢! –

回答

1

clear()通常不是一个好的函数名称来定义。它与document.clear冲突。

还记得你总是可以只使用<input type="reset" value="clear"/>这可能是更简单! :)

function clearIt() { 
 
document.getElementById('customerName').value = ""; 
 
}
<table border="1" id="orderForm"> 
 
    <tr> 
 
    <th colspan="2">Customer Details</th> 
 
    </tr> 
 
    <tr> 
 
    <td id="font">Customer Name</td> 
 
    <td><input type="text" id="customerName"></td> 
 
    </tr> 
 
</table> 
 

 
<button type="button" id="button1" onClick="clearIt()">Clear</button>

+0

稍作编辑以容纳@ sweaver2112关于'document.clear'的非常有用的信息 – mayersdesign

-1

首先调用jQuery库,然后执行以下代码,而不是你一个

$document.ready(function(){ 
$("button1").click(function(){ 
document.getElementById("#customerName").value=""; 
}); 
}); 

我喜欢把所有的JavaScript body标签结束前。

0

正如@Pratyush已经提到的,变化的函数名称到别的东西 - 你的代码将正常工作。

0

只是要清楚,clear()完全有效的香草的JavaScript。

它只是恰巧document定义clear()也:

enter image description here

...并因为你的HTML属性分配click处理获取与修改作用域链执行,该document对象clear()来作用域链全局函数之前(从Javascript权威指南):

然而,注册为HTML属性的事件处理程序是一种特殊情况。它们被转换成顶级函数,它们可以访问全局变量 ,但不能访问任何局部变量。但是,对于 历史原因,他们运行一个修改的范围链。由HTML属性定义的事件处理程序 可以使用 目标对象的属性,包含对象(如果有的话),并且 文档对象,如同它们是局部变量。

,然后他讨论您的确切情况:

HTML事件处理程序的修改的范围链是 缺陷的来源,因为每个对象的链中的 阴影的性质的任何性质全局对象中的同名名称。所述 文献对象定义一个(很少使用)open()方法,例如,使 想要调用 Window对象的open()方法的HTML事件处理程序必须明确地写出的window.open而不是开放

所以,你的函数可以通过window.clear()在HTML达到:

function clear() { document.getElementById("customerName").value=""; 
 
}
<table border="1" id="orderForm"> 
 
    <tr> 
 
     <th colspan="2">Customer Details</th> 
 
    </tr> 
 
    <tr> 
 
     <td id="font">Customer Name</td> 
 
     <td><input type="text" id="customerName"></td> 
 
    </tr> 
 
</table> 
 

 
<button type="button" id="button1" onClick="window.clear()">Clear</button>