[英]How do I get the element containing clicked text in Javascript/Jquery?
I would like to replace the text on pages when I click on the text or even just replace the single word clicked on. 当我单击文本时,我想替换页面上的文本,甚至只是替换单击的单个单词。 I have tried a top down approach selecting all elements in the DOM, filtering out the textNodes, wrapping each with tags and adding a click event handler to each tag.
我尝试了一种自上而下的方法,选择DOM中的所有元素,过滤掉textNodes,用标签包装每个标签,并向每个标签添加click事件处理程序。 But this is far too slow and inefficient particularly on very large and dynamic sites.
但这太慢且效率低下,特别是在非常大且动态的站点上。
I only need to replace the text that was clicked. 我只需要替换单击的文本。 Is there a bottom up way of doing this starting from the event.target?
从event.target开始,是否有一种自下而上的方法? How do I find the closest textNode to the event.target, for example?
例如,如何找到最接近event.target的textNode?
In the example you gave, you can just do the following; 在您给出的示例中,您可以执行以下操作; for more info see How do I select text nodes with jQuery?
有关更多信息,请参见如何使用jQuery选择文本节点?
$(document).click(function(event) {
textNodes = $(event.target).contents().filter(function() {
return this.nodeType == 3;
});
textNodes.each( function() {
$(this).replaceWith("New Text");
});
})
Have you tried Jquery's .closest() ? 您是否尝试过Jquery的.closest() ?
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. 说明:对于集合中的每个元素,通过测试元素本身并遍历DOM树中的其祖先,获得与选择器匹配的第一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.