如何获取动态表id值并将其传递给javascript函数

时间:2016-01-18 12:53:04

标签: javascript html html-table

我需要你的帮助来获取表的id值并将值传递给javascript函数。我在表中有一个图像,我想点击它,要捕获的表的id并将其传递给javascript函数。这是表格代码:

<table class="tablesorter" id="detailsTable<%=tableCounter%>" width="80%">
<tr>
<td>
<a href="javascript:fnExcelReport();">
<img border="0" src="../Images/excel_icon.png" alt="Export to Excel"></a>
</td>
</tr>
</table>

我需要将id传递给它的javascript函数(第7行):

<script type="text/javascript">
function fnExcelReport()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('detailsTable1'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

</script>

2 个答案:

答案 0 :(得分:1)

这解决了这个问题:

  <table class="tablesorter" id="detailsTable<%=tableCounter%>" width="80%">
            <tr>
                <td>
                    <img onclick="fnExcelReport(this);" border="0" src="../Images/excel_icon.png" alt="Export to Excel">
                </td>
            </tr>
        </table>

和javascript代码:

 function fnExcelReport(ele) {
                var tableid = ele.parentNode.parentNode.parentNode.parentNode.id;
                // etc.
            }

答案 1 :(得分:0)

你必须得到图像的parentElement.id(触发器)。

您可以在图片中添加class以确保这是想要的图片。

一个快速而又脏的片段:

<img class="trigger" border="0" src="../Images/excel_icon.png" alt="Export to Excel"></a>

window.addEventListener("click", function(e){ //instead of window you can also add your element
    if (e.target.className == "trigger"){
        var table = e.target.parentElement.parentElement.parentElement.parentElement;
        fnExcelReport(table.id;);

        }
    })

THEN:

function fnExcelReport(id)
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById(id); // id of table

...