我有一个 Sharepoint 2013 列表,什么是 html 表格。有一个带有超链接的列。如果用户单击此列中的任何超链接并获取单击的超链接的行索引,我想触发一个事件。一切都是由 SP 自动生成的,所以很困惑,看起来链接上没有 id。超链接表的 html 的一部分:(我希望这足以以某种方式确定 rowindex)
<td id="scriptWPQ2">
<table onmousedown="return OnTableMouseDown(event);" summary="TestList" xmlns:o="urn:schemas-microsoft-com:office:office" o:webquerysourcehref="&XMLDATA=1&RowLimit=0&View=%7BEA3CDF07%2D1A28%2D4A44%2DBCB2%2D01F7D45A76C0%7D" border="0" cellspacing="0" dir="none" onmouseover="EnsureSelectionHandler(event,this,14)" cellpadding="1" id="{7632DCD3-4F1B-4F8E-AC8C-FB9C4372CD3D}-{EA3CDF07-1A28-4A44-BCB2-01F7D45A76C0}" class="ms-listviewtable" handledeleteinit="true">
<tbody>
<tr class=" ms-itmHoverEnabled ms-itmhover" oncontextmenu="return ShowCallOutOrECBWrapper(this, event, false)" iid="14,312,0" id="14,312,0" setedgeborder="true">
<td class="ms-cellstyle ms-vb2">
<a href="/sites/Registry">copy</a> //no id here :(
另外一个问题是,表格默认只显示 30 个元素,并且页面底部有一个下一个按钮,如果按下,表格将显示下一个 30 个元素。因此,即使在按下按钮后,单击事件也应该触发。我可以通过单击 tabe 的任何元素来获取 rowindex,但这在某种程度上只适用于前 30 个项目:
$(document).ready(function()
{
$("tr").click(function (){
alert($("tr").index(this));
});
});
我的最终目标是读取单击行中的所有其他项目,并将它们带到超链接重定向的页面。遗憾的是我没有 JS 经验,并且已经浪费了几个小时的失败,所以请帮我一把!非常感谢您的热心帮助!
当使用第一个答案中的建议代码正常工作时:
2.页面加载后仍然可以工作:
最佳答案
方法如下event delegation/propagation在 jQuery 中工作:
$('table').on('click', 'a', function (e) {
// Make sure the browser doesn't follow the link
e.preventDefault();
console.log($(this).parent().parent().index());
});
即使您向表格主体添加新行,单击链接仍会显示行索引。
<强> DEMO
以下是在原生 JS 中执行此操作的方法:
// Attach an event listener to the table element
let table = document.querySelector('table');
table.addEventListener('click', checkRowOfAnchor, false);
function checkRowOfAnchor(e) {
// check to see if the clicked element is a link
// prevent the browser from following the link
// log the row index to the console
if (e.target.tagName === 'A') {
e.preventDefault();
console.log(e.target.parentNode.parentNode.rowIndex);
}
}
<强> DEMO
关于javascript - 如何为超链接点击添加事件并获取点击对象的rowindex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222688/