我正在动态创建一个表格,希望每一行都可单击并链接到一个 URL,并在单击后打开该 URL。
我想出了创建表格并将每一行设置为可点击行的 Bootstrap 。
// Table Body
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
var IntegrityURL = "integrity://lanwinsvmks1.eu.adglob.net:8001/im/viewissue?selection=";
var ReqURL = IntegrityURL.concat(rowData[0]);
row.setAttribute("class", "clickable-row");
row.setAttribute("href", ReqURL);
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
var context = getColor(cellData);
cell.setAttribute("bgcolor",context);
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
我还在doc.ready中设置了点击功能:
$('#OverviewTable tr').click(function() {
var href = $(this).find("tr").attr("href");
if(href) {
window.location = href;
}
});
html 中的结果看起来正确,但该行不可点击,并且未调用 click() 函数。
我错过了什么?
最佳答案
您可以尝试以下操作:如果您有任何问题,请在下面发表评论。
$('.clickable-tr').on('click', function(){
var myLink = $(this).attr('href');
window.location.href = myLink;
});
.clickable-tr{
cursor: pointer;
background: #eee;
}
table{
width: 100%;
}
thead tr th{
text-align: left;
}
tr td{
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody>
<tr class="clickable-tr" href="https://stackoverflow.com">
<td>
Data 1 example
</td>
<td>Data 1 Example</td>
</tr>
<tr class="clickable-tr" href="https://stackoverflow.com">
<td>
Data 2 example
</td>
<td>Data 2 Example</td>
</tr>
</tbody>
</table>
更新:说明
在 js
代码中,我们的目标是具有 clickable-tr
类的元素。然后使用 $(this)
,我们说将选择唯一的当前元素/点击。然后使用 attr()
,我们获取当前的 href
属性,并使用 window.location.href
进行重定向。
关于javascript - 将 Bootstrap 可点击行与 href 链接连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46295582/