Getting table id
I am using jquery and my goal is to get the id of next table. I will simplify the code here:
The simplified HTML looks like this:
<div>
<img src="png.png" class="exportIcon" alt='' onClick="tableExport()">
<table class="table tablesorter" id="tableHourlyT"><tr><td></td></tr></table>
</div>
And I then have the following function:
<script>
function tableExport(){
tableID = $(this).next('table').attr("id");
alert(tableID);
}
</script>
But the alert says "undefined" and in fact I cant even do anything with the table, I tried hiding it etc. It just doesnt find it. I also tried replcing the "next()" with "closest()" but I still had the same result. What I need to do is always when the function is called, get the id of the closest following table from that element (clicked image/button)
Here's one way to do what you want - pass the element as an argument to the tableExport function:
<div>
<img src="png.png" class="exportIcon" alt='' onClick="tableExport(this)">
<table class="table tablesorter" id="tableHourlyT"><tr><td></td></tr></table>
</div>
Then, use that in a jQuery selector:
<script>
function tableExport(element){
tableID = $(element).next('table').attr("id");
alert(tableID);
}
</script>
You shouldn't use the onClick attribute, but rather use a jQuery event handler:
$(".exportIcon").click(tableExport); //bind tableExport as the handler whenever an export icon is clicked function tableExport() { ... }When you bind the event that way, you'll find that $(this) is correctly set to the element that was clicked.
http://www.codeply.com/go/y6OAZFRZSn
(I replaced your img with a button for the demo, but it would work the same.)
Also use:
var tableID = $(element).next('table').attr("id");
instead:
tableID = $(element).next('table').attr("id");
Variable without var prefix will be defined in global scope
链接地址: http://www.djcxy.com/p/83316.html下一篇: 获取表格ID