简体   繁体   English

获取JQuery中的clicked元素

[英]Get clicked element in JQuery

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. 我有100行和10列,我想获取td和tr对象,我想检查天气表中是否已选择文本。

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").val($.trim(st));
  }
}

Instead of binding mouseUp for document bind it for td elements, 与其为文档绑定mouseUp而不是为td元素绑定它,

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

You need to check event.target . 您需要检查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). 请注意,如果每个表单元格中都有一个或多个子元素,则需要从event.target上走到DOM树,直到到达td元素为止(否则,单击不位于单元格外部)。

You can get the clicked element in the mouseup event by doing this: 通过执行以下操作,可以在mouseup事件中获取clicked元素:

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

    var $clickedElement = $(event.target);

The clicked element may be any element inside the td. clicked元素可以是td内部的任何元素。 You can get the td itself with this: 您可以使用以下命令获取td本身:

// 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() 参见event.target.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. 现在,单击的td或tr元素存储在称为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: 请注意,这将返回用户单击的每个元素,因此您必须检查它是td还是tr元素,如下所示:

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

Does this help ? 这有帮助吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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