javascript 在 JQuery 中获取被点击的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7215282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:19:54  来源:igfitidea点击:

Get clicked element in JQuery

javascriptjquerymouseevent

提问by OHLáLá

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));
  }
}

回答by Jayantha Lal Sirisena

Instead of binding mouseUpfor document bind it for tdelements,

与其mouseUp为文档绑定,不如为td元素绑定,

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

回答by Arnaud Le Blanc

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

您可以通过执行以下操作在 mouseup 事件中获取单击的元素:

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:

单击的元素可以是 td 内的任何元素。您可以通过以下方式获取 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.targetand .closest()

参见event.target.closest()

回答by Matthew

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.targetuntil you reach a tdelement (or not, in which case the click was outside a cell).

你需要检查event.target。请注意,如果您在每个表格单元格中有一个或多个子元素,则您需要沿着 DOM 树向上走,event.target直到到达一个td元素(或者没有,在这种情况下,单击位于单元格之外)。

回答by Some Guy

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:

现在被点击的 td 或 tr 元素存储在名为 elem 的全局变量中。请注意,这将返回用户单击的每个元素,因此您必须检查它是 td 还是 tr 元素,如下所示:

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

回答by Trefex