【问题标题】:Jquery .each iteration accessing this subcontentsJquery .each 迭代访问此子内容
【发布时间】:2018-07-15 04:44:05
【问题描述】:

我想搜索所有列表项并仅显示包含特定短语的列表项。

然而,我已将内容放在一个跨度中。 这意味着我的列表看起来有点像这样:

<ul class="sortable">
<li><span>search keywords here</span>A lot of code possibly here. Some divs and some other elements</li>
</ul>

而且我或多或少想用下面的代码来过滤。

var filter = $('#search_page_query').val(), count = 0;    

$(".sortable li").each(function () {

    if ($(this).text().search(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();


    } else {
        $(this).show();
        count++;
    }
});

这只有在列表项直接包含搜索关键字时才有效。

事实并非如此。我应该使用以下内容搜索列表项:

$(this + 'span').text()

但这当然是不正确的。但我不知道如何正确访问跨度内容。 我希望任何人都可以告诉我它是如何完成的。

提前致谢


@RameshKithsiriHettiArachchi解决

解决办法是

而不是:

$(this).text()

使用:

$(this).children('span').text()

完整代码:

var filter = $('#search_page_query').val(), count = 0;    

$(".sortable li").each(function () {

    if ($(this).children('span').text().search(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();


    } else {
        $(this).show();
        count++;
    }
});

【问题讨论】:

  • 你试过$(this).children('span')吗?
  • @RameshKithsiriHettiArachchi 谢谢!!!那行得通!如果您添加是作为答案,我可以接受!不知道这样你有没有额外的声望!但如果是这样。 :D 谢谢!
  • @AlexHakkenberg 感谢您的声誉!我已经回答了。帮个忙。 :-)
  • 不要在您的问题中回答您的问题,而是将其移至下面的答案,并将其标记为解决方案

标签: jquery arrays foreach


【解决方案1】:

使用$(this).children()函数选择当前DOM元素的子元素。

https://api.jquery.com/children/

【讨论】:

  • 还有很多其他方法可以实现这一点,您最好使用$(this).find("&gt;span").text()$("&gt;span", this).text() 而不是.children()。但这主要是微观管理。请参阅此处了解更多信息:stackoverflow.com/a/27234084/2181514
猜你喜欢
  • 2010-12-14
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 2011-09-12
相关资源
最近更新 更多