简体   繁体   中英

How to get a first cell from a row that user hovers over?

How to get a first cell from a row that user hovers over and then clicks certain key combination?(i am thinking about using jQuery) I have a table that is similar to that one. When user places mouse over any of tr's and press ctrl+c he gets the ID copied to his clipboard. Thank you! UPD.Code that worked bellow.

<table>
   <tr>
    <td>ID</td>
    <td>Text1</td>
    <td>Text2</td> 
    <td>Text3</td> 
   </tr>
   <tr>
    <td id="my_id">1</td>
    <td>Example1</td>
    <td>Example1</td> 
    <td>Example1</td> 
   </tr>
   <tr>
    <td id="my_id">2</td>
    <td>Example2</td>
    <td>Example2</td> 
    <td>Example2</td> 
   </tr>
   <tr>
    <td id="my_id">3</td>
    <td>Example3</td>
    <td>Example3</td> 
    <td>Example3</td>
   </tr>
</table>

$(document).ready(function()
{
    var ctrlDown = false;
    var ctrlKey = 17, cKey = 67;
    var id = "";

    $(document).keydown(function(e)    {
        if (e.keyCode == ctrlKey) ctrlDown = true;
    });
    $("tr").mouseover(function(){
        id = $(this).find("#my_id").html(); 

    });
    $("tr").mouseout(function(){  
       id = "";
    });
    $(document).keydown(function(e)
    {
        if (ctrlDown && e.keyCode == cKey) {
            if (id != "") {
                window.prompt("Copy to clipboard: Ctrl+C, Enter", id);
                ctrlDown = false;
            }
        }
    });
});

Welcome to Stackoverflow. First of all, please read the guidelines on how to ask a question.

Key of this guideline is:

stackoverflow members won't do your work, but they'll help you, if you are stuck with a problem. To help you, we would need a 'What have I done so far' passage inside your question.

Now to your problem.

Do you know jquery? and how the selectors work? here the steps for your what have I done passage:

  • The table row selector $("table tr") (but I'd suggest working with classes and id's)

  • The jquery hover function

  • The selector to get the first cell:

     $("> td:first", this) 
  • The jquery function to get the content of the first td .

  • The clipboard problem, already discussed here .

You can get the cell value in different ways. Below is the simple script that does that.

JSFIDDLE: http://jsfiddle.net/kiranvarthi/cr399ww2/ (click to see value alert)

$( "table tr" ).click(function() {
    alert($(this).children('td').first().html());
});

Once you get the ID, you can just add to clip board. Below link help to do that. How do I copy to the clipboard in JavaScript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM