如何在单击链接时获取行值

时间:2014-05-06 14:55:52

标签: javascript html

我有一个包含3行的表,每行都有href。单击这些链接,我需要获取单击链接的行的整个值。

Data
Test1_link   image_link   view-link
Test2_link   image_link   view-link

上面的数据是链接,点击任意链接时,应该呈现其对应的行值。 任何人都可以建议我如何实现这一目标吗?

感谢。

2 个答案:

答案 0 :(得分:2)

您可以在表格后面放置一个简单的脚本:

<script>
  (function (d) {

     // Get the table element
     var table = function() {
       var tables = d.getElementsByTagName('table');
       return tables[tables.length - 1];
     }();

     table.onclick = function (e) {
       var target = e.target;

       // If an <a> was clicked
       if( target.nodeName.toLowerCase() === 'a' ) {

         // Find the tr containing that a
         var node = target;
         while (node.nodeName.toLowerCase() !== 'tr' )
           node = node.parentNode;
         var tr = node;

         // Output the contents of the table cells in that row
         var cells = tr.cells;
         for (var i = 0; i < cells.length; i++ )
             console.log(cells[i].innerHTML);

         // Return false to prevent the link from loading
         return false;
       }
     }
  })(document)
</script>

JSFiddle

答案 1 :(得分:0)

使用jQuery http://www.jquery.com尝试此操作。

<table class="js-mytable">
    <tr data-id="23" data-something="you've got it!">
        <td>
            <a href="javascript:;">Test Link</a>
        </td>
        <td>
            <a href="javascript:;">Image Link</a>
        </td>
        <td>
            <a href="javascript:;">View Link</a>
        </td>
    </tr>
</table>

<script>
    //run after document ready event
    $(function(){
        //all links in table with class js-mytable
        $('table.js-mytable').on('click','a',function(){
            //var $cell = $(this).parents('td'); //get the parent td of the link
            var $row = $(this).parents('tr'); //get the parent tr of the link
            //get the html5 data attributes from the row
            var id = $row.data('id');
            var something = $row.data('something');

            //do something with the vars
            //alert('Id: '+id+': '+something);

            //get the full html <tr>...</tr>
            //we need to merge it to a new pseudo html element
            //to get the full html with surrounding <tr>
            var html = $('<div>').append($row.clone()).html();
            alert(html);

            return false; //prevent default link action (href)
        });
    });
</script>

如果您需要更多详细信息,则需要扩展您的问题......

JsFiddle:http://jsfiddle.net/7ud43