简体   繁体   English

遍历每个表行并向其中添加超链接

[英]Traversing Each table row and adding hyperlink to it

My Table is getting dynamically generated through Jquery DataTable . 我的表通过Jquery DataTable动态生成。 Which looks something like this: 看起来像这样:

<table id ="mySearchResults">
    <tr>
        <td>MyName</td>
        <td>MyPlace</td>
        <td>Status</td>
    <tr>
    <tr>
        <td>MyName1</td>
        <td>MyPlace1</td>
        <td>Status1</td>
    <tr>
</table>

I want to traverse the whole table but only want to check 2nd or some other column value (consider this table to be quiet big, so I want to access by index). 我想遍历整个表,但只想检查第二个或其他某个列的值(考虑到该表要安静一些,所以我想按索引访问)。 If its value corresponds to something, then I would like to add a hyperlink to the whole row which calls a Jquery function, where I can access all the values of that particular row. 如果其值与某值相对应,那么我想在整个行中添加一个超链接,该超链接调用Jquery函数,在该行中我可以访问该特定行的所有值。

I tried something like, It doesn't seem to be working. 我尝试了类似的方法,它似乎没有用。 Any inputs appreciated. 任何输入表示赞赏。

$('#mySearchResultstr').each(function() {
    var value = $(this).find('td 6').val();   //Consider 6 to 6th column
    if(value='abc'){                          //Check if it is abc
        $(this).parent.add                    //Not sure what function to call to add hyperlink to a local jquery function. 
    } 
});

Btw. 顺便说一句。 my rows can not have an anchor tag by default. 默认情况下,我的行不能包含锚标记。 Only based on value of certain column, it should have hyperlink. 仅基于某些列的值,它应该具有超链接。

Also how can I make sure, this traversing happens once the table is loaded, since the table is loaded via AJAX. 另外,由于表是通过AJAX加载的,因此如何确保这种遍历在表加载后发生。

Well instead of traversing each table row separately you can take advantage of "createdRow" parameter of DataTable . 很好,而不是单独遍历每个表行,您可以利用DataTable"createdRow"参数。

At the time of table creation you can check the values of the required column and assign the respective function as link to that row as below 在创建表时,您可以检查所需列的值,并将相应功能分配为该行的链接,如下所示

Demo : https://jsfiddle.net/Prakash_Thete/xck2jys3/5/ 演示: https : //jsfiddle.net/Prakash_Thete/xck2jys3/5/

Example taken for demonstration in Fiddle : 在Fiddle中进行演示的示例:

//HTML
<table id="item" width="100%" cellspacing="0">
      <thead>
           <tr>
               <th>Name</th>
               <th>Age</th>
               <th>Start date</th>
               <th>Salary</th>
           </tr>
       </thead>
</table>


//JS

var tableData = [
        [   "Tiger Nixon",
            "61",
            "2011/04/25",
            "$320,800"
        ],
        [
           "Garrett Winters",
           "63",
           "2011/07/25",
           "$170,750"
        ],
       [
         "Ashton Cox",
         "66",
         "2009/01/12",
         "$86,000"
       ]
   ]; 

var itemTable = $("#item").DataTable({
     "data":tableData,
     "createdRow": function ( row, data, index ) {

       // you can check value of the any column you want 
       // I have checked the "age" column value
       if(data[1] > 62){
            $(row).attr("data-href", "greaterThanSixtyTwo");
       } else {
            $(row).attr("data-href", "lessThanSixtyTwo");
       }
    }
});   

//click event handler for row 
$('#item tbody').on( 'click', 'tr', function () {
    //fetch the row data
    var rowData = itemTable.row( this ).data();

    //fetch the function to be called on click of this row
    var functionToCall = $(this).data("href");

    //call the function with clicked rows data 
    eval( functionToCall + "( '"+rowData +"' )" );
});

function greaterThanSixtyTwo(rowData){
  console.log(" I am greater than Sixty Two - > : ", rowData);
}

function lessThanSixtyTwo(rowData){
  console.log("I am less than Sixty Two - > : ", rowData);
}

You most likely want to use .append() or .prepend() methods of jQuery element: 您最可能想使用jQuery元素的.append().prepend()方法:

// Iterating over <tr> elements, which are descendants of your table
$("#mySearchResultstr tr").each(function () {
    // $thisRow will contain a reference to a <tr> element
    // wrapped in jQuery Object
    var $thisRow = $(this);

    if (YOUR_CONDITION_HERE) {
        // Create new Link
        var $link = $("<a/>");
        $link.attr("href", YOUR_URL);
        $link.text("SOMETHING");

        // Use append or prepend, depends on where you want to insert the link
        $thisRow.append($link);
    }
});

Try this : 尝试这个 :

$(document).ready(function() {

    $("tr").each(function(){

        var href = "yourHref";
        var name = "your name";

        var value  = $("td",this).eq(5).text();

        if(value == 'abc') {
            $(this).html("<td colspan=6><a href=" + href + ">" + name + "</a></td>" );
        }

    })

})

Final code : 最终代码:

 <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <table border="1"> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>abc</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>abc</td></tr> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(document).ready(function() { $("tr").each(function(){ var href = "yourHref"; var name = "your name"; var value = $("td",this).eq(5).text(); if(value == 'abc') { $(this).html("<td colspan=6><a href=" + href + ">" + name + "</a></td>" ); } }) }) </script> </body> </html> 

Description 描述

  1. Delegate click event to #btn 将点击事件委托给#btn
  2. content is whatever is entered in #in1 To be matched with #result 's <td> content content是在#in1中输入的content#result<td>内容匹配
  3. url is an address entered in #in2 url是在#in2输入的地址

  4. If user did not enter a url, the default will be used: http://www.example.com 如果用户未输入网址,则使用默认值: http://www.example.com : http://www.example.com

  5. Next, each <td> will be searched to see if any content entered by user is matched with the content of each <td> 接下来,将搜索每个<td>以查看用户输入的任何内容是否与每个<td>的内容匹配

  6. Any <td> that is matched, will have it's text wrapped in a dynamically created anchor which will include a predetermined url (by user input or default see #3 and #4). 任何匹配的<td>都将其文本包装在动态创建的锚中,该锚将包含预定的url(通过用户输入或默认设置,请参见#3和#4)。

  7. ✎ On each <td> we will do the following: ✎在每个<td>我们将执行以下操作:

    • Collect all siblings name them $sisters . 收集所有兄弟姐妹将其命名为$sisters
    • On $sisters change the background to yellow. $sisters将背景更改为黄色。
    • Find parent <tr> and assign it as $mom . 查找父<tr>并将其分配为$mom
    • Each $mom will get an id = "row" + idx . 每个$mom将获得一个id = "row" + idx idx corresponds to <td> index position within the table (0 zero count). idx对应于表中的<td>索引位置(0零计数)。 Use devtools to inspect the <tr> to see what I'm talking about. 使用devtools检查<tr>以了解我在说什么。

✎ Upon further reading of OP's request I have improved my answer to include <tr> and sibling <td> manipulation. ✎在进一步阅读OP的请求后,我已将答案改进为包括<tr>和同级<td>操作。 Also, the default url function has been disabled see #4 and source for details. 另外,默认的url功能已被禁用,有关详细信息,请参见#4和来源。


References 参考


Examples 例子

PLUNKER PLUNKER

SNIPPET SNIPPET

 <!DOCTYPE html> <html> <head> <style> body { font: 400 16px/1.428 Consolas; } #results { border: 2px solid grey; } td { border: 1px solid black; padding: 5px; } a { color: yellow; background: #000; display: inline; transition: all 1s; text-decoration: none; } a:hover { color: #000; background: yellow; display: block; transition: all 1s; text-decoration: underline; } </style> </head> <body> <fieldset> <legend>Query Content</legend> <input id='in1' type='search' placeholder='LOC5' search='5'> <button id='btn1'>Search</button> <input id='in2' placeholder='http://google.com'> <br/> <small>Search function is case-sensitive</small> </fieldset> <table id="results"> <tr> <td>NAME4</td> <td>LOC4</td> <td>STATUS4</td> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> </tr> <tr> <td>NAME4</td> <td>LOC4</td> <td>STATUS4</td> <td>NAME2</td> <td>LOC2</td> <td>STATUS2</td> </tr> <tr> <td>NAME3</td> <td>LOC3</td> <td>STATUS3</td> <td>NAME2</td> <td>LOC2</td> <td>STATUS2</td> </tr> <tr> <td>NAME4</td> <td>LOC4</td> <td>STATUS4</td> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> </tr> <tr> <td>NAME5</td> <td>LOC5</td> <td>STATUS5</td> <td>NAME2</td> <td>LOC2</td> <td>STATUS2</td> </tr> <tr> <td>NAME5</td> <td>LOC5</td> <td>STATUS5</td> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> </tr> <tr> <td>NAME4</td> <td>LOC4</td> <td>STATUS4</td> <td>NAME2</td> <td>LOC2</td> <td>STATUS2</td> </tr> <tr> <td>NAME3</td> <td>LOC3</td> <td>STATUS3</td> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> </tr> <tr> <td>NAME2</td> <td>LOC2</td> <td>STATUS2</td> <td>NAME4</td> <td>LOC4</td> <td>STATUS4</td> </tr> <tr> <td>NAME5</td> <td>LOC5</td> <td>STATUS5</td> <td>NAME3</td> <td>LOC3</td> <td>STATUS3</td> </tr> <tr> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> <td>NAME5</td> <td>LOC5</td> <td>STATUS5</td> </tr> <tr> <td>NAME2</td> <td>LOC2</td> <td>STATUS2</td> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> </tr> <tr> <td>NAME3</td> <td>LOC3</td> <td>STATUS3</td> <td>NAME5</td> <td>LOC5</td> <td>STATUS5</td> </tr> <tr> <td>NAME4</td> <td>LOC4</td> <td>STATUS4</td> <td>NAME1</td> <td>LOC1</td> <td>STATUS1</td> </tr> <tr> <td>NAME5</td> <td>LOC5</td> <td>STATUS5</td> <td>NAME3</td> <td>LOC3</td> <td>STATUS3</td> </tr> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <script> /* | 1. Delegate click event to #btn | 2. content is whatever is entered in #in1 | To be matched with #result's <td> content | 3. url is an address entered in #in2 | 4.✎ If user did not enter a url, the default | will be used: http://www.example.com | 5. Next, each <td> will be searched to see | if any content entered by user is matched | with the content of each <td> | 6. Any <td> that is matched, will have it's | text wrapped in a dynamically created | anchor which will include a predetermined | url (by user input or default see #3 and #4 */ $('#btn1').on('click', function() { var content = $('#in1').val(); var url = $('#in2').val(); /* Uncomment if default url is desired if (url === 'undefined' || url === null || url === '') { url = 'http://www.example.com'; } */ /* | 7. On each `<td>` we will do the | following: | a. Collect all siblings name them | $sisters. | b. On $sisters change the background | to yellow. | c. Find parent `<tr>` and assign it | as $mom. | d. Each $mom will get an id='row'+idx. | idx corresponds to `<td>` index | position within the table (0 zero count). | Use devtools to inspect the `<tr>` to | see what I'm talking about. */ $('td').each(function(idx) { var $sisters = $(this).siblings(); var $mom = $(this).parent(); if ($(this).text() === content) { $(this).wrapInner('<a href="' + url + '"></a>'); $sisters.css('background', 'yellow'); $mom.each(function() { $(this).attr('id', 'row' + idx); }); } }); }); </script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM