[英]Add OnClick Event with JavaScript or CSS
我有一個HTML表:
<table id="cust">
<tr>
<th>UserName</th>
<th>Password</th>
</tr>
<script type="text/javascript">addRows();</script>
</table>
並且我在JS中有將行插入此表的功能。 例如:
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
但我希望插入到表中的每一行都具有如下onClick事件:
<tr onclick="window.document.location='Accounts.html';">
我怎樣才能做到這一點?
謝謝 !!
您可以使用此-
row.setAttribute( “點擊”, “window.document.location = 'Accounts.html'”);
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.setAttribute("onclick","window.document.location='Accounts.html'");
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
由於您未使用任何jQuery構造,因此在行元素中添加了onlick處理程序
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.onclick = rowClick
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
function rowClick() {
window.document.location = 'Accounts.html';
}
如果您想擁有不同的目標位置,那么
function addRows() {
// Get a reference to the table
var table = document.getElementById("cust");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.onclick=function(){
window.document.location='Accounts.html';
}
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = "ilan";
cell1.innerHTML = "11111";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.