2015-01-04 78 views
0

有一个字符串如下“100200300400500”。 我想把它分成3个子集,比如“100”“200”“300”“400”“500”。 我希望他们作为顺序的子元素的鼠标悬停标题/工具提示。 这就是当你将鼠标悬停在第一个孩子上时,工具提示应该说100,并且当你将鼠标悬停在第二个孩子上时,工具提示应该说200,等等。 这里的结果= 100200300400500 和str =结果字符串长度为3的子字符串为什么不是循环工作?

以下是我迄今为止取得的成果。但所有的孩子divs的工具提示读取100. 我做错了什么?

 $.ajax({ 
     url: "https://dl.dropboxusercontent.com/u/47127613/ajax.txt", 
     dataType: "text", 
     success: function(result) { 
      var str = result; 
      if (str.length > 3) str = str.substring(0, 3); { 
       for (var n = 1; n < 100; n++) { 
        $("#parent:nth-child(n)").children().attr('title', str + ' Installs'); 
        for (var i = 0; i < 100; i++) { 
         str(i) = str(i + 3); 
        } 
       } 
      } 
     } 
    }); 

HTML

<div id="parent"> 
    <div class="child1"></div> 
    <div class="child2"></div> 
    <div class="child3"></div> 
    <div class="child4"></div> 
    <div class="child5"></div> 
    </div> 
+0

你能发布HTML结构呢? – 2015-01-04 11:28:26

+0

当然。编辑了这个问题。 – 2015-01-04 11:29:09

+1

代码中有很多bug。 – tom10271 2015-01-04 11:32:18

回答

0

n的值不被在一个字符串解释为它的。你的选择应该是这个样子:$("#parent:nth-child(" + n + ")")

+0

我试过了,但那不行。 – 2015-01-04 11:31:37

-1

要访问数组单元格,你应该写:

str[i]; //not str(i) 
0

你应该通过div元素循环和分配title属性。

var str = '100200300400500'; 
 
// Initialize the counter 
 
var c = 0; 
 
// Loop through all 'div's that are direct child of '#parent' 
 
$('#parent > div').each(function() { 
 
    // Assign the 'title' attribute to the current 'div'($(this)). 
 
    // The 'str.substring(c, c + 3)' will extract a sub string from 
 
    // the current index(c) till 3 more indexes(c + 3). 
 
    $(this).attr('title', str.substring(c, c + 3) + ' Installs'); 
 
    // Increment the counter by 3. 
 
    c += 3; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="parent"> 
 
    <div class="child1">One</div> 
 
    <div class="child2">Two</div> 
 
    <div class="child3">Three</div> 
 
    <div class="child4">Four</div> 
 
    <div class="child5">Five</div> 
 
</div>

+0

我已经尝试了两个选择器,但所有的工具提示都显示了字符串的前3个字母。 – 2015-01-04 11:37:54

+0

小心解释一下什么没有帮助,这样我可以改进? – 2015-01-04 11:43:40

+0

嘿!这种作品,但不是每个孩子的div,但留下一个缺口。 – 2015-01-04 11:48:09

1

你可以使用这个片段尝试分裂。那是你需要的吗?

var r = [], str = "100200300400500"; 
 
// you may want to check for appropriate str.length 
 
// if (str.length % 3 != 0) { ... } 
 
str.split('') 
 
    .map(function (v, i, arr) { 
 
     void(i && (i % 3 == 0 || i == arr.length-1) 
 
       ? this.push(
 
        i == arr.length -1 ? arr.slice(-3) 
 
             : arr.slice(i-3, i)) 
 
       : null); 
 
     return v; 
 
     }, r); 
 
document.querySelector('#result').innerHTML = 
 
    r.map(function (v) {return v.join('')}).join('<br>');
<div id="result"></div>