使用Jquery而不是函数来访问表中的数据
Use Jquery Instead of Functions to Access Data From Table
我们一直在使用javascript函数将数据从表传递到我们需要处理该行数据的任何地方。例如,以以下表格为例:
<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>
通常,我们只需要以下函数来处理按行更改的数据(通常传递一个id,但有时函数中可能有一堆args)。这个函数可以做各种各样的事情——当然不仅仅是这些例子。
function myfunc(f_ID, f_Name) {
alert(f_ID + "_" + f_Name);
$.colorbox({ iframe: true, overlayClose: true, opacity: .70, inline: false, fixed: true, title: "Colorbox Title", href: "/mypage.asp?id=" + f_ID + "&name=" + f_Name });
}
或
function myfunc(f_ID, f_Name) {
if (confirm("Are you sure that you would like to permanently delete id # " + f_ID + " for " + f_Name + "?")) {
window.location = "/mypage.asp?id=" + f_ID + "&name=" + f_Name
}
}
我知道像这样混合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"));
}
首先:计算出如果JS不可用,您希望发生什么。
一个普通的链接就可以了。
<a href="/mypage.asp?id=1&name=Jack">edit</a>
您不需要在代码中分别使用id和名称,只需在页面本身显示的URL中使用它们,并且您可以直接从链接中读取URL。
this
(在事件处理程序中)是指用于触发事件的元素。
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") );
…但是遍历DOM…
var name = jQuery(this).parents("tr").find("td:first-child").text();
…或者使用为您正在使用的特定数据设计的属性(如果存在)会更好。
相关文章:
- 如何使用React JS中的循环,根据条件渲染或不渲染表数据
- Ajax更新表数据,但不重复顺序
- 如何从javascript访问表单数据
- 如何在 Angularjs 中访问表单值
- 访问HTML数据集
- 如何使用模板访问角度数据表中的当前行数据
- 通过jquery(coffeescript)访问表数据
- 使用Jquery而不是函数来访问表中的数据
- 访问表单控制AngularJS中的值,而不绑定数据
- 访问表单数据值
- 如何在Angularjs中访问表单提交的数据
- 如何在不使用对象文字值的情况下从setter访问表单数据
- 我怎样才能轻松地访问表单数据在Express js
- 我如何从jQuery .submit()事件对象访问表单POST数据
- 我如何访问API数据(Python,请求)在我的HTML表的特定单元格
- 如何在Angularjs中使用复选框函数访问表数据
- 如何访问嵌套的html表数据
- jQuery数据表插件-如何访问底层数据
- 如何访问AlloyUI数据表中的选定行
- 如果不使用bodyParser,您将如何访问表单数据