【问题标题】:how to select one single text from multiple text inside html tags with css selector?如何使用css选择器从html标签内的多个文本中选择一个文本?
【发布时间】:2017-01-05 16:25:34
【问题描述】:
<span class="filter-dot hidden"></span>
Brand <span class="filter-count hidden">(0)</span>
<input type="hidden" class="js-filter-count" value="0">
<span class="filter-clear hidden" data-displaytype="checkBox">
Clear
</span>

我只想选择“品牌”,但当我使用$('div.filter-type-name').text(); 时,它会选择“品牌”和“清除”。谁能建议我如何只选择“品牌”?

【问题讨论】:

  • 您的代码与您的声明不匹配
  • 根据您的代码 sn-p $('div.filter-type-name').text();不会返回任何内容
  • 将品牌包装到另一个跨度中并仅选择此跨度。
  • 你没有 div.filter-type-name
  • 对不起,实际上代码以
    开头,然后是问题中写的内容。

标签: javascript jquery html css


【解决方案1】:

将“品牌”包装到一个更具体的选择器中并仅选择它:

<div class="filter-type-name">
  <span class="filter-dot hidden"></span>
  <span class="filter-name">Brand</span>
  <span class="filter-count hidden">(0)</span>
  <input type="hidden" class="js-filter-count" value="0">
  <span class="filter-clear hidden" data-displaytype="checkBox">Clear</span>
</div>

然后:

$('div.filter-type-name .filter-name').text()

否则,使用childNodes集合遍历它并选择您需要的(Node.TEXT_NODE === 3),但这不是很实用:

$('div.filter-type-name')[0].childNodes

【讨论】:

  • 我不能修改html代码实际上它是snapdeal的部分(移动列表页面url:snapdeal.com/products/mobiles-mobile-phones?sort=plrty)源代码,我正在抓取。
  • 所以选择$('div.filter-type-name')[0].childNodes。对文本节点的简单迭代将为您提供所需的内容。
【解决方案2】:

要么给Brand 自己的周围元素加上一个类或id,说“品牌”然后做:

$('div.filter-type-name .brand-name').text()

或保持原样并执行:

$('div.filter-type-name').text().split(' ')[0];

【讨论】:

    【解决方案3】:

    THIS ONE 好像解决了。

    这是 JSFiddle: https://jsfiddle.net/flamedenise/9dsfbkms/

    var text = ($(".filter-type-name").clone().children().remove().end().text()).trim();
    alert(text);
    

    【讨论】:

    • 我无法修改 html 代码实际上它是 snapdeal(移动列表 page.url:snapdeal.com/products/mobiles-mobile-phones?sort=plrty)源代码的一部分,我是做刮。
    • 对不起。请在上面查看我的编辑,让我知道它是否有效。
    【解决方案4】:

    无需将您的“品牌”字符串包装到标签中。您可以使用以下方法。

    假设这是你的代码:

    <div class="filter-type-name"> 
     <span class="filter-dot hidden"></span>
     Brand 
     <span class="filter-count hidden">(0)</span>
     <input type="hidden" class="js-filter-count" value="0">
     <span class="filter-clear hidden" data-displaytype="checkBox">  Clear </span>
    </div>
    

    您可以使用正则表达式匹配脚本来检查您想要的文本。

    var str = $('div.filter-type-name').text(); 
    var res = str.match(/Brand/g);
    

    要查看输出,

    <p id="demo"> </p>
    document.getElementById("demo").innerHTML = res;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2014-03-01
      • 1970-01-01
      • 2011-06-04
      • 2023-01-29
      相关资源
      最近更新 更多