开发者

Why I can not get the row id when mouse clicked on a table row?

I have a index.html page with a table:

<bo开发者_Go百科dy>
      <table class="mytable">
          <tr id="1">
              <td>John</td>
              <td>123</td>
          </tr>
           <tr id="2">  
              <td>Kate</td>
              <td>456</td>
          </tr>
      </table>

  <script src="my.js"></script>
  </body>

I have included my.js in my page, I tried to get the id of the mouse clicked row in the following way in my.js:

$('.mytable tr').click(function(e){
                   alert('clicked.'); //even did not get alert here.
                   var rowId = $(this).attr('id');
               alert(rowId);
        });

But I did not get the row id of clicked row(no alert), where am I wrong?

---Solution---

My bad, I have one place emptied the table, which means no tr at all. that's why it does not work. Sorry for bothering.


  1. $ === jQuery ?
  2. Is the code which binds the click listener executed in a document ready handler?
  3. this.id is sufficient and will work in all browsers.


This seems to work just fine... Here's a working JSFiddle that uses alert instead of console.log:

http://jsfiddle.net/gfosco/KtYkJ/

Based on the comments and Matt's answer, you should wrap your function like this:

$(document).ready(function() {
    $('.mytable tr').click(function(e){
               var rowId = $(this).attr('id');
           alert(rowId);
    });
});

The javascript was executing before the DOM was ready and therefore the handler was not being applied.


It's working for me.

What do you get if not the id?

The most common problem is that the event handler isn't binding to the element, for which the most common solution is to wrap it in $(document).ready(){ ... } so that it waits for the DOM to load before binding to elements.

(There's also the relatively recent .live() function which binds to elements as they get added in the life of the document.)


first you must check your js file path that it is correct or not? if this is correct then i think there is no any error in your script .. i also tested it ... you can check it Demo


Change your event handler to

$('.mytable tr').each(function() {
    $(this).click(function() {
        var rowId = $(this).attr("id");
        alert(rowId);
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜