简体   繁体   English

Javascript / Jquery:获取元素内char的索引

[英]Javascript / Jquery: get index of char within element

Is there a simple way to get the index of a char within an element? 是否有一种简单的方法来获取元素内char的索引? For example, if I'm looking at the first span below, then I want to know that its first char is the seventh char within the li. 例如,如果我正在查看下面的第一个跨度,那么我想知道它的第一个字符是li内的第七个字符。 I will only need to know this for chars within an element (no textnodes), but there may be textnodes, and their chars do "count". 我只需要知道元素中的字符(没有textnodes)的字符,但是可能会有textnode,它们的字符“计数”。

<li id = "li">
    <p>0123</p>
    <div>4
      <span id = "span">5</span>
      <span>67</span>
    </div>
    8
</li>

Edit: Added IDs to the elements above. 编辑:将ID添加到上述元素。 then something like: 然后是这样的:

index = getIndexOfFirstChar($("#span"), $("#li"))

Note that the chars are not unique. 请注意,字符不是唯一的。 I used numbers, but it could be any text. 我使用数字,但是可以是任何文本。

You can do this by using a mix of .text() (to get inner text without HTML), .replace() (to remove whitespace) and .indexOf() to get the index: 您可以通过使用的混合做到这一点.text()获得无HTML内部文本), .replace()删除空格)和.indexOf()来获得指标:

var clearTextWithNoWhitespace = $('li').text().replace(/\s+/g, '');
var index = clearTextWithNoWhitespace.indexOf('5');

console.log(clearTextWithNoWhitespace); //012345678
console.log(index); //5

JSFiddle DEMO JSFiddle演示

If you want to include whitespace: 如果要包含空格:

var index = $('li').text().indexOf('5');
console.log(index); //22

JSFiddle DEMO JSFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM