2015-01-04 112 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>

相關問題