【问题标题】:Traversing Each table row and adding hyperlink to it遍历每个表行并为其添加超链接
【发布时间】:2017-01-26 07:42:07
【问题描述】:

我的表是通过Jquery DataTable 动态生成的。看起来像这样:

<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>

我想遍历整个表,但只想检查第二列或其他一些列值(考虑这个表很大,所以我想按索引访问)。如果它的值对应于某些东西,那么我想为调用 Jquery 函数的整行添加一个超链接,我可以在其中访问该特定行的所有值。

我尝试了类似的方法,它似乎不起作用。任何输入表示赞赏。

$('#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. 
    } 
});

顺便说一句。默认情况下,我的行不能有锚标记。仅基于特定列的值,它应该有超链接。

此外,我如何确保一旦加载表就会发生这种遍历,因为表是通过 AJAX 加载的。

【问题讨论】:

  • 你搞定了吗?
  • 是的,普拉卡什。谢谢,你的代码很好。我避免了很多不必要的 JavaScript 代码。

标签: javascript jquery html hyperlink datatables


【解决方案1】:

试试这个:

$(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>" );
        }

    })

})

最终代码:

<!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>

【讨论】:

  • 我不需要添加一个新元素,即超链接。相反,我希望将整行超链接到某些东西。
  • @Crawling,我更新帖子。看看它,如果你能标记我的答案。
  • 感谢您的回复。您的解决方案有效。但我的要求略有不同。学到了一些东西。谢谢!
【解决方案2】:

说明

  1. 将点击事件委托给#btn
  2. content 是在 #in1 中输入的任何内容 与#result&lt;td&gt;内容匹配
  3. url#in2中输入的地址

  4. 如果用户没有输入网址,则默认 将使用:http://www.example.com

  5. 接下来会搜索每个&lt;td&gt;看 如果用户输入的任何内容匹配 带有每个&lt;td&gt;的内容

  6. 任何匹配的&lt;td&gt; 都会有 包含在动态创建的文本中 锚将包括一个预定的 url(由用户输入或默认见 #3 和 #4)。

  7. ✎ 对于每个&lt;td&gt;,我们将执行 以下:

    • 收集所有兄弟姐妹的名字 $sisters
    • 开启$sisters改变背景 变黄。
    • 找到父&lt;tr&gt;并分配它 作为$mom
    • 每个$mom 都会得到一个id = "row" + idxidx 对应于 &lt;td&gt; 索引 表中的位置(0 零计数)。 使用 devtools 检查 &lt;tr&gt; 以 看看我在说什么。

✎ 在进一步阅读 OP 的请求后,我改进了我的答案,包括&lt;tr&gt; 和兄弟&lt;td&gt; 操作。此外,默认的 url 功能已被禁用,请参阅 #4 和源以获取详细信息。


参考文献


示例

PLUNKER

片段

<!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>

【讨论】:

  • 感谢您的详细回复。信息量很大!
【解决方案3】:

您可以利用DataTable"createdRow" 参数,而不是单独遍历每个表行。

在创建表时,您可以检查所需列的值并将相应的函数分配为该行的链接,如下所示

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

在 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);
}

【讨论】:

  • 非常干净的代码。适用于我当前的数据表实现。非常感谢。
【解决方案4】:

您很可能希望使用 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);
    }
});

【讨论】:

  • 只是一个澄清。这会追加新行还是新单元格,或者只是使当前行可点击?
  • 最终结果将是这样的:&lt;td&gt;Status&lt;a href="YOUR_URL"&gt;SOMETHING&lt;/a&gt;&lt;/td&gt;(我已在答案中添加了 SOMETHING 部分)。
  • 感谢您的回复。不过我的要求略有不同。
猜你喜欢
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 2019-05-08
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
相关资源
最近更新 更多