【问题标题】:jQuery - Use Body Text As SelectorjQuery - 使用正文文本作为选择器
【发布时间】:2015-04-20 10:33:45
【问题描述】:

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

例子:

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

【问题讨论】:

    标签: javascript jquery html text typeerror


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 不是还会选择图片和文字以外的其他东西吗?
    • 这就是我建议您将事件附加到正文然后对您不希望事件发生的元素使用 stopPropogation 的原因。看到这个帖子stackoverflow.com/questions/10389459/…
    【解决方案2】:

    你可以把你的正文放在<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!");
    });
    

    【讨论】:

    • 如果文本的唯一包装是body 标记和图像等其他内容,而我只想选择文本怎么办?
    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 2011-03-04
    • 1970-01-01
    • 2010-12-11
    • 2011-12-16
    • 2011-04-26
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多