简体   繁体   English

如何获取包含Javascript / Jquery中单击文本的元素?

[英]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.

相关问题 Javascript / jQuery - 如何获取clicked元素类的名称? - Javascript/jQuery - How do I obtain name of the class of clicked element? 如何获取(和使用)在javascript / jQuery中被单击的元素? - How do I grab (and use) the element being clicked in javascript/jQuery? 如何获取使用 jQuery 单击的动态加载的元素 - How do I get the dynamically loaded element that was clicked with jQuery 如何使用内联HTML onclick和jQuery获取单击的元素? - How do I get the clicked element with inline HTML onclick and jQuery? 如何使用jQuery获得点击的元素文本? - how to get clicked element text using jQuery? 如何在 JavaScript 中获取首先单击哪个元素以及其次单击哪个元素? - How do I get which element is clicked first and which element is clicked second in JavaScript? 如何使用Jquery编写“如果未单击”或“如果在外部元素上单击”? - How do I write 'if not clicked' or 'if clicked outside element', using Jquery? 如何获取在Javascript中单击的文本? - How can I get the text that was clicked on in Javascript? 如何隐藏与没有jQuery时单击的元素最接近的元素? - How do I hide the closest element to the element that was clicked without jQuery? 当使用Jquery / JavaScript单击上一个列表项时,如何定位嵌套在列表项内的元素? - How do I target an element nested inside a list item when the previous list item is clicked with Jquery/JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM