开发者

Get clicked element in JQuery

开发者 https://www.devze.com 2023-03-31 09:00 出处:网络
I\'m using the following code to get the selected text, my question is, how can I get the element where the text was selected? I have 100 rows and 10 columns and I want to get the td and tr object and

I'm using the following code to get the selected text, my question is, how can I get the element where the text was selected? I have 100 rows and 10 columns and I want to get the td and tr object and I want to check weather the text was selected inside the table.

function getSelectedText() {
  var t = '';
  if(window.getSelection){
    t = window.getSelection();
  }else if(document.getSelection){
    t = document.getSelection();
  }else if(document.selection){
    t = document.selection.createRange().text;
  }
  return t;
}
$(document).bind("mouseup", putSelectedToInput);

function putSelectedToInput(){
  var st = getSelectedText();

  if(st!=''){
    $("#params_oldname").v开发者_如何学Goal($.trim(st));
  }
}


Instead of binding mouseUp for document bind it for td elements,

$('td').mouseUp(function(){
 var selectedTd=$(this);
});


You need to check event.target. Be aware that if you have one or more child elements in each table cell, you need to walk up the DOM tree from event.target until you reach a td element (or not, in which case the click was outside a cell).


You can get the clicked element in the mouseup event by doing this:

function putSelectedToInput(event){ // notice the event parameter

    var $clickedElement = $(event.target);

The clicked element may be any element inside the td. You can get the td itself with this:

// returns the closest parent that is a td (or the element itself if it's a td)
var $theTd = $clickedElement.closest('td');

See event.target and .closest()


Simply use:

document.onclick=function(){
elem = window.event.srcElement
}

Now the td or tr element which was clicked in is stored in the global variable called elem. Note that this would return every element in which the user has clicked, so you would have to check if it was a td or tr element, like so:

if(elem.tagName.toLowerCase() == "td" || elem.tagName.toLowerCase() == "tr")


Does this help ?

http://api.jquery.com/get/

0

精彩评论

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