我正在使用一些基于以下JSFiddle 的代码。目的是在用户单击“显示额外”链接时显示更多信息。
我遇到的问题是,当点击链接时,除了表格的底行之外,隐藏的元素会短暂显示,然后关闭。
我正在使用 javascript 中的模板字符串填充我的表。这是我用来向表中添加行的代码:
this.addRecordToTable = function(bet, index, id){
console.log(index);
console.log($.data(bet));
var butId = id.toString();
if (bet.bookies == null){
bet.bookies = "";
}
if (bet.bet == null){
bet.bet = "";
}
var newRow = `
<tr>
<td>${bet.date}</td>
<td>${bet.bookies}</td>
<td>${bet.profit}</td>
<td><button id=${butId}>Delete</button></td>
<td><a href=\"#\" id=\"show_${index}\">Show Extra</a></td>
</tr>
<tr>
<td colspan=\"5\">
<div id=\"extra_${index}\" style=\"display: none;\">
<br>hidden row
<br>hidden row
<br>hidden row
</div>
</td>
</tr>
`
console.log(newRow);
console.log("#"+butId);
$(newRow).appendTo($("#betTable"));
$("#"+butId).click(
function()
{
if (window.confirm("Are you sure you want to delete this record?"))
{
var rec = new Records();
rec.removeRecordAt(index);
$("#betTable tbody").remove();
var c = new Controller();
c.init();
}
});
$("a[id^=show_]").click(function(event) {
$("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
event.preventDefault();
});
}
编辑:
我不得不更改$("a[id^=show_]").click
为$("a[id=show_"+index).click...
,因为每次添加新元素时都会将事件处理程序添加到每个元素。感谢@freedomn-m。
这段代码:
$("a[id^=show_]")
向每个现有链接以及新链接添加一个新的事件处理程序,因为它不是特定于 ID/上下文的,因此所有 show 都a
与选择器匹配。
您需要添加上下文 ( newRow
) 或使用现有变量作为已定义循环的一部分,例如:
$("a[id^=show_]", newRow)
$("a#show_" + index)
(或任何其他有效的变体)。
另一种方法是对动态添加的元素使用偶数委托,例如:
$(document).on("click", "a[id^=show_]", function...
在这种情况下,您只需要定义/调用一次事件,它就会为新元素触发(即,将其放在新行循环之外)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句