如何用jQuery选择每个第n个字符的父元素?

时间:2015-05-04 17:33:03

标签: javascript jquery html

我有以下结构:

<div id="container">
<p class="p-one">Some paragraph text. Some paragraph text.</p>
<p class="p-two">Some paragraph text. Some paragraph text.</p>
<p class="p-three">Some paragraph text. Some paragraph text.</p>
<p class="p-four">Some paragraph text. Some paragraph text.</p>
<p class="p-five">Some paragraph text. Some paragraph text.</p>
</div>

使用jQuery,我希望能够在一定数量的字符之后以编程方式选择父元素(因此在这种情况下,这将是段落之一)。例如,如果数字是70,我希望能够计算#container中的所有字符然后找到第70个字符并选择字符所属的元素,在这种情况下将是段落与班级名称&#39; p-two&#39;。如果数字是120,它会做同样的事情,但然后选择段落&#39; p-three&#39;。 (我这样做的目的是让我可以分解一个长容器元素,里面有许多不同的元素,直到粗略等大小的块。)

使用.length我可以很好地计算#container的字符,然后选择遇到麻烦的父。

2 个答案:

答案 0 :(得分:0)

您不必确定整个#container元素的文本长度,而是必须在p元素本身上执行此操作。您可以循环执行此操作:

var $children = $('#container').children(),
    $selected,
    limit = 70,
    len = 0;

$children.each(function() {
    len += $(this).text().length;

    if (len > limit) {
        $selected = $(this);
        return false;
    }
});

这里我们有一个len变量。 each()循环遍历p中的每个#container元素,并将len中存储的值增加该特定p中包含的文本的长度元件。如果len变得大于我们的限制,我们将$selected元素设置为当前迭代元素并跳出循环。

演示

var $children = $('#container').children(),
    $selected,
    limit = 70,
    len = 0;

$children.each(function() {
  len += $(this).text().length;

  if (len > limit) {
    $selected = $(this);
    return false;
  }
});

$selected.css('background', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <p class="p-one">Some paragraph text. Some paragraph text.</p>
  <p class="p-two">Some paragraph text. Some paragraph text.</p>
  <p class="p-three">Some paragraph text. Some paragraph text.</p>
  <p class="p-four">Some paragraph text. Some paragraph text.</p>
  <p class="p-five">Some paragraph text. Some paragraph text.</p>
</div>

答案 1 :(得分:-1)

尝试

&#13;
&#13;
var container = $("#container"); 
var stop = 70; var idx = null;

container.text(function(i, text) {
  var arr = text.split("\n").filter(Boolean);
  var n = 0;
  $.each(arr, function(key, elem) {
    n = n + elem.length;
    console.log(n, key)
    if (n > stop) {
      idx = key;
      return false;
    };
  });
});

container.find("p").eq(idx).css("background", "yellow");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<p class="p-one">Some paragraph text. Some paragraph text.</p>
<p class="p-two">Some paragraph text. Some paragraph text.</p>
<p class="p-three">Some paragraph text. Some paragraph text.</p>
<p class="p-four">Some paragraph text. Some paragraph text.</p>
<p class="p-five">Some paragraph text. Some paragraph text.</p>
</div>
&#13;
&#13;
&#13;