2017-04-20 65 views
0

我有一個按鈕,就像下面,提交按鈕在HTML和JS

<button type = "submit">submit</button> 

我怎麼JS讀,它已經被按下不改變的HTML代碼?

我也有一個按鈕,是

<button class="add">add</button> 

如何讓JS讀取點擊而無需修改代碼?

+0

無需更改HTML代碼MEANS ?? –

回答

2

你會選擇使用哪個的幾個DOM元素選擇功能(.querySelector().getElementsByTagName().getElementsByClassName()等),一個需要你的想象元素,附加一個事件偵聽click事件,然後在監聽器做任何你想。

// document.querySelector('button.add') to select by class, or... 
 
document.querySelector('button[type="submit"]').addEventListener('click', function(e) { 
 
    alert('The button was clicked.') 
 
})
<button type = "submit">submit</button>

需要注意的是,如果你有在頁面上有多個按鈕,那麼你就需要使用.querySelectorAll()(或我提到的其他功能之一),以在返回一個列表,然後循環將事件處理程序附加到每個事件處理程序的列表。或者把一個處理程序附加到它們的通用包含元如果你想爲做一些不同的,那麼你需要一些方法來區分它們,例如,如果它們在不同的容器或其他東西。

0
var buttons=document.getElementsByTagName("button");////returns an array of all buttons 
//assuming that you have only one button with type == submit otherwise loop here 
if(buttons[0].getAttribute("type")=="submit") 
{ 
buttons[0].addEventListener("click",function(){ 
    //you code goes here 
}); 
} 


var buttons=document.getElementsByClassName("add");//returns an array of buttons with class as add 
//assuming that you have only one button with class add 
buttons[0].addEventListener("click",function(){ 
    //you code goes here 
});