jQuery Onclick事件在特定h2包含特定文本

jQuery Onclick event on specific h2 containing specific text

本文关键字:h2 文本 包含特 Onclick 事件 jQuery      更新时间:2023-09-26

我有一个div,它已经被动态地包含在我的页面中,所以我不能访问它,因为它不在我的当前页面上。

是这样的:

<h2 class="title">About</h2>

我需要做的是添加一个'onclick'事件,针对这个div。

我只知道它是一个'h2',类'title',文本包含'About'。

我该怎么做?

你可以使用:contains来选择包含的文本,像这样:

$("h2.title:contains('About')").click(function(e) {
    // Handle here
});

使用

$(document).on('click','h2.title', function(e){ 
    if(e.currentTarget.textContent.trim() == "About") {
    //write your code here
    }
});

您可以使用.filter进行特定匹配。因为:contains也会匹配<h2 class="title">About Us</h2>

$("h2.title").filter(function () {
    return $.trim($(this).text()) == "About";
}).click(function(e) {
});