Javascript 使用Jquery而不是函数从表中访问数据
我们一直在使用javascript函数将数据从表传递到我们需要对该行数据执行的任何操作。例如,以下表为例:Javascript 使用Jquery而不是函数从表中访问数据,javascript,jquery,Javascript,Jquery,我们一直在使用javascript函数将数据从表传递到我们需要对该行数据执行的任何操作。例如,以下表为例: <table class="table table-hover table-striped"> <thead> <tr> <th>Name</th> <th>Action</th> </tr> <
<table class="table table-hover table-striped">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jack</td>
<td><a href="javascript:myfunc(1,'Jack')">edit</a></td>
</tr>
<tr>
<td>Dan</td>
<td><a href="javascript:myfunc(2, 'Dan')">edit</a></td>
</tr>
<tr>
<td>Mark</td>
<td><a href="javascript:myfunc(3, 'Mark')">edit</a></td>
</tr>
</tbody>
</table>
或
我知道,像这样混合使用Jquery和老式的JS可能不是最好的方法(也许这很好??),所以一定有更好的方法来访问这些数据
我想我可以使用“data-”标记,但问题是当有多行时,如何实际获取值?我不能使用ID,因为它是唯一的,如果我添加了一个类,如何从调用中访问数据
任何帮助都将不胜感激,谢谢
更新
这就解决了我的问题。谢谢@Quentin
<a class="testlink" href="#" data-id="1234">edit</a>
$("a.testlink").on("click", myAction);
function myAction(event) {
event.preventDefault();
alert($(this).data("id"));
}
$(“a.testlink”)。点击(“点击”,myAction);
函数myAction(事件){
event.preventDefault();
警报($(this).data(“id”);
}
首先:确定如果JS不可用,您希望发生什么
一个普通的链接就可以了
<a href="/mypage.asp?id=1&name=Jack">edit</a>
如果确实需要传递其他数据,则可以通过以下方式从数据属性中读取:
<a href="/mypage.asp?id=1&name=Jack" data-somedata="foo">edit</a>
…
function openColorBox(event) {
event.preventDefault();
alert( jQuery(this).data("somedata") );
…或者使用为您正在使用的特定数据设计的属性(如果存在)会更好。据我所知,最好的方法是使用.closest()。下面的链接定义了您需要的内容。这将为彩盒工作-谢谢张贴。如果图片中没有彩色框呢?也许我只是想导航到一个页面(见上面添加的示例)或处理页面上的某些内容?当您有250行数据时,如何访问“数据somedata”?您如何知道单击了哪行中的哪个“编辑”按钮或链接?例如:data id=“1”,data id=“2”,etcIf您“使用想要导航到一个页面”,然后使用链接。“处理页面上的某些内容”-太模糊了,不能说,这也不起作用,因为我并不总是访问实际表本身中的数据。var name=jQuery(this).parents(“tr”).find(“td:first child”).text();假设这是特定于从未显示的行的数据。“如何访问“data somedata”—请参见答案中的示例,开头是“如果确实需要传递其他数据,则可以从数据属性中读取”
<a href="/mypage.asp?id=1&name=Jack">edit</a>
jQuery(function() {
$("a").on("click", openColorBox);
function openColorBox(event) {
event.preventDefault();
var url = this.href;
$.colorbox({
iframe: true,
overlayClose: true,
opacity: .70,
inline: false,
fixed: true,
title: "Colorbox Title",
href: url
});
}
});
<a href="/mypage.asp?id=1&name=Jack" data-somedata="foo">edit</a>
…
function openColorBox(event) {
event.preventDefault();
alert( jQuery(this).data("somedata") );
var name = jQuery(this).parents("tr").find("td:first-child").text();