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

时间:2015-02-19 06:56:42

标签: javascript jquery html text typeerror

我们如何使用texts内部body元素作为选择器,就像任何其他选择器一样(即:id,类,输入等)?当身体中的任何文字被悬停或点击时,我想做点什么。

示例:

$("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

2 个答案:

答案 0 :(得分:0)

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

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

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

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

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

答案 1 :(得分:0)

你可以将你的正文放在<span> or <p>标签中,并且可以在jquery中轻松附加mouseover事件,即:

HTML:

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

JQuery的:

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