【发布时间】:2020-01-20 21:19:33
【问题描述】:
我的 JavaScript 函数被多个 CGI 脚本调用,因此我想将特定于脚本的 HTML id 属性作为参数传递给我的函数。然后,在函数体中,我想在 jQuery 快捷方式中使用包含此参数的参数。但是,当我使用 jQuery 语法时,我的参数一直被解释为字符串文字。
写出长格式的 JavaScript 来使用参数是可行的,但是因为我在其他任何地方都使用 jQuery 快捷方式,所以我也想在这种情况下使用相同的语法。每个页面可以有多个表格,因此在表格元素上进行选择将不起作用。我找不到任何我想要完成的文档。在 Perl 中,这类似于使用 ${parameter_name} 而不是 $parameter_name。
deleteItem.cgi (Perl):
my $rows;
my $counter = 0;
for (@array) {
$rows .= "
<tr id='del$counter' class='bg-dark' onclick='setRowBackground(\'deleteItems\', $counter)'>
<td>$_</td>
</tr>
";
$counter++;
}
<head>
<script type="text/javascript" src="setBackground.js"></script>
</head>
<body>
<table id="deleteItems" class="bg-dark">
$rows
</table>
</body>
setBackground.js:
$(function() {
// this uses the id name and is what I am trying to avoid so that
setBackground.js can be used by multiple CGI scripts //
$('#deleteItems').DataTable();
});
function setRowBackground(tableID, rowNumber) {
// after removing class "bg-dark"
none of these work: //
$("#tableID").DataTable().row(rowNumber).nodes().to$().addClass("bg-white");
$(#"tableID").DataTable().row(rowNumber).nodes().to$().addClass("bg-white");
$(#tableID).DataTable().row(rowNumber).nodes().to$().addClass("bg-white");
$(#(tableID)).DataTable().row(rowNumber).nodes().to$().addClass("bg-white");
// these do work:
...but this one can only be used for a table with this id, and table ids
are not consistent accross multiple CGI scripts! //
$(#deleteItems).DataTable().row(rowNumber).nodes().to$().addClass("bg-white");
// ...but this one is what I am trying to avoid since the rest of the code
uses jQuery. //
document.getElementById(tableId).DataTable().row(rowNumber).nodes().to$().addClass("bg-white");
}
【问题讨论】:
-
$("#tableID")应该是$("#" + tableID)。变量不会在字符串中展开,您需要将它们连接起来。 -
太棒了,巴尔玛!成功了,谢谢。
标签: javascript jquery perl parameter-passing