2017-04-16 85 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>