jQuery 获取列表中父项的文本

jQuery get Text of parent in list

我有以下列表

$(document).ready(function() {
  $('li').click(function(e) {
    alert($(e.target).children().remove().end().text());
    alert($(e.target).siblings('span:first').text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <span>foo1</span>
    <span style="visibility: hidden">bar1</span>
  </li>

  <li>
    <span>foo2</span>
    <span style="visibility: hidden">bar2</span>
  </li>

  <li>
    <span>foo3</span>
    <span style="visibility: hidden">bar3</span>
  </li>
</ul>

我想在不同的值中同时提取 "foo1" 和 "bar1"。上面的函数看起来很奇怪。有人能找到更好的方法吗?

你能调整我的 jQuery 功能吗?

您应该试试这个代码:

$(document).ready(function() {
  $('li').click(function() {
    console.log('span #1', this.children[0].innerHTML);
    console.log('span #2', this.children[1].innerHTML);
  });
});

你需要找到()跨度,然后做文本()或html()

$(document).ready(function() {
  $('li').click(function(e) {
    alert($(e.currentTarget).find('span:last-child').text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  

    <li>
    <span>foo1</span>
    <span style="visibility: hidden">bar1</span>
  </li>

  <li>
    <span>foo2</span>
    <span style="visibility: hidden">bar2</span>
  </li>

  <li>
    <span>foo3</span>
    <span style="visibility: hidden">bar3</span>
  </li>
</ul>

您可以使用 find('span:first').text() 获取带有 foo 的文本:

$(document).ready(function() {
  $('li').click(function(e) {
    console.log($(this).find('span:first').text());
  });
});
I have the following list $(document).ready(function() { $('li').click(function(e) { alert($(e.currentTarget).text()); }); });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <span>foo1</span>
    <span style="visibility: hidden">bar1</span>
  </li>

  <li>
    <span>foo2</span>
    <span style="visibility: hidden">bar2</span>
  </li>

  <li>
    <span>foo3</span>
    <span style="visibility: hidden">bar3</span>
  </li>
</ul>

Expand snippet I would like to get only the "foo".text() of each list element clicked. With my actual approach I also receice the "bar".text() unfortunately. Could you adjust my jQuery function please? javascript jquery target shareeditcloseflag asked
6 mins ago AppRoyale 1281217

您可以阅读更多关于 find() here and about text() here