jQuery-使用正文文本作为选择器

jQuery - Use Body Text As Selector

本文关键字:选择器 文本 正文 jQuery-      更新时间:2024-01-10

我们如何使用body元素中的所有texts作为选择器,就像任何其他选择器一样(即:id、class、input等)?当正文中的任何文本被悬停或单击时,我想做一些事情。

示例:

$("body > text").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

我试过这个:

$("body").text().on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

但它返回了这个错误:

TypeError: $(...).text(...).on is not a function

您可以将正文放在<span> or <p>标签中,并可以在jquery中轻松附加鼠标悬停事件,即:

HTML:

<body>
<p>this is text</p>
</body>

JQuery:

$("body p").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

您的第一个事例没有附加事件,因为没有带标记名文本的元素。第二个失败,因为jquery .text()返回字符串,并且on方法用于dom元素的jquery对象,这给您带来了错误。

您只需将事件附加到body元素即可。:

$("body").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});

还可以使用all选择器将事件附加到所有内部元素:

$("body *").on('mouseover', function(){
 alert("Any text in the body is hovered!");
});