使用Jquery而不是函数来访问表中的数据

Use Jquery Instead of Functions to Access Data From Table

本文关键字:访问表 数据 函数 Jquery 使用      更新时间:2024-04-18

我们一直在使用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&amp;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&amp;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();

…或者使用为您正在使用的特定数据设计的属性(如果存在)会更好。