为什么循环不工作?

时间:2015-01-04 11:26:26

标签: javascript jquery html jquery-selectors

有一个字符串如下" 100200300400500"。 我试图将它分成3个子集,如" 100" " 200" " 300" " 400" " 500&#34 ;. 我希望它们按顺序用作子元素的鼠标悬停标题/工具提示。 那就是当你将鼠标悬停在第一个孩子上时,工具提示应该说100,当你将鼠标悬停在第二个孩子上时,工具提示应该说200,依此类推。 结果= 100200300400500 和str =结果字符串

的长度为3的子字符串

以下是我迄今取得的成就。但是所有子div上的工具提示都是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>

4 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码段进行拆分。这就是你需要的吗?

&#13;
&#13;
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>');
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

n的值不会被解释为字符串中的值。您的选择器应如下所示:$("#parent:nth-child(" + n + ")")

答案 2 :(得分:0)

您应循环遍历div元素并分配title属性。

&#13;
&#13;
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;
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

要访问Array单元格,您应该写:

str[i]; //not str(i)
相关问题