遍历(获取)元素包装在 <a> 标记内

Traverse(get) elements wrapped inside <a> tag?

本文关键字:元素 包装 遍历 获取      更新时间:2023-09-26

我有这样的东西:

<a class="feature category">
            <div class="feature-txt left">
                <p id="first">innerHTML</p>
            </div>
            <div class="feature-go left center">
                <i class="fa fa-angle-right fa-fw"></i>
            </div>
        </a>

单击我想在 p 标签内获取文本,但是:

$('.category').on('click', function() {
            alert($(this).find("p").innerHTML);
        });

不工作。我怎样才能得到它?

$(this).find("p") 返回 DOM 元素的 jQuery 对象。 你不能直接在它们上使用JavaScript方法。

1)将对象转换为javascript

$('.category').on('click', function() {
    alert($(this).find("p")[0].innerHTML);
});

2)或使用jquery的.text().html()方法

$('.category').on('click', function() {
        alert($(this).find("p").text());
    });

使用以下代码。 使用 jquery 的 .text() 或 .html() 函数

  $('.category').on('click', function() {
        alert($(this).find("p").text());
  });

 $('.category').on('click', function() {
        alert($(this).find("p").html());
  });

不起作用,因为div和p不是标签的子节点。

你还是被误解了。根据您的标记,可以很容易地说divp是锚点的子节点。

问题是.innerHTML javascript方法中,您将此方法绑定到jQuery对象,而您需要有一个DOM Node才能使用它,因此您可以使用[0]后缀将其转换为DOM Node,或者在jquery中使用.get(0)

使用innerHTML

$('.category').on('click', function() {
    alert($(this).find("p")[0].innerHTML);
    alert($(this).find("p").get(0).innerHTML);
});

或者另一种方法是使用jQuery的.html(), .text(),它也做同样的事情:

$('.category').on('click', function() {
    alert($(this).find("p").html());
    alert($(this).find("p").text());
});