开发者

Storing IDs of table rows

sorry to bother some of you again. But I still haven't found a working answer to my problem.

I have a good old fashioned HTML table. Each reach has its unique ID. What I want to achieve with JavaScript is that this ID gets stored in a variable once I cklick a link on each row.

Mi开发者_开发技巧ght sound easy to you, I am new to JS and I can't figure it out to the end. Could someone help me please?

Thanks!


The Onclick event of what you are clicking on can call a function like

function RecordClick( elem ) {
    mylocalVar = elem.id;
}

by saying onclick="RecordClick(this);"


When you create your table on the server-side you put this in your HTML (as I understand your scenario):

...
<tr>
    <td>
        <a href="...">Some link name</a>
    </td>
</tr>
...

So why not do this:

<script>
    var rowID = -1;
</script>
...
<tr>
    <td>
        <a href="javascript: rowID = 111; void(0);">Some link name</a>
    </td>
</tr>
...

This is not the best way of doing it, but it gets the job done. If you're using some library like jQuery, you could do it in a completely different way and using closures as well.


you have to take a global variable for this. U can take it into the head section like-

var idHolder;

Now in the table onclick handler u call a function like-

table onclick="extractId(obj)">

The function definition may be like this-

function extractId(var obj) { idHolder=obj.Id; }

This will do ur work, in case of any problem reply.


Since the click event bubbles up the DOM, you can do this by hooking the click event of the table, and then figuring out which row was clicked. This is usually called "event delegation." Something like this (live copy):

// Hook click on the table
document.getElementById('theTable').onclick = function(e) {
  var element;

  // Handle IE vs. standards
  e = e || window.event;

  // Find out what was clicked (more IE vs. standards)
  element = e.target || e.srcElement;

  // Find the row
  while (element && element.tagName !== "TR") {
    element = element.parentNode;
  }

  // Found it?
  if (element) {
    // Yes, remember the ID and show it
    targetVariable = element.id;
    display("You clicked row " + targetVariable);
  }
};

Off-topic: This stuff is made a lot easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others. For instance, the above code using jQuery looks like this:

$('#theTable').click(function(event) {
    var target = $(event.target).closest('tr');
    if (target.length > 0 ) {
        targetVariable = target[0].id;
        display("You clicked row " + targetVariable);
    }
});

Live copy

Or using one of the new features:

$('#theTable').delegate('tr', 'click', function(event) {
    targetVariable = this.id;
    display("You clicked row " + targetVariable);
});

Live copy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜