2015-06-30 9 views
1

我想找到II,III,I,d,F和CP下表中使用jQuery的數量。首先,我正在考慮使用正則表達式,但它不適用於我。我只是一個初學者,這是我迄今爲止所嘗試的。查找和計數字符串使用jQuery

表:

<table> 
    <tr> 
    <th>Sl</th> 
    <th>Name</th> 
    <th>status</th> 
    <th>position</th> 
    </tr> 
    <?php while($row= $dbh->fetch(PDO::FETCH_ASSOC)){ 
    <tr> 
    <td><?php echo $row['id'];?></td> 
    <td><?php echo $row['nm'];?></td> 
    <td class="st"><?php echo $row['st'];?></td>//Regular AND private 
    <td class="ps"><?php echo $row['ps'];?></td>//output-CP, I, II, III, D, F 
    </tr> 
<?php } ?> 
</table> 

的Jquery:

var ps = $('.ps').text();//output is IIIIIIDIIIICPIIIIIIDIICPIIFIIII 
var compt = ps.match(/CP+/g); 
$(".inbody").text(compt.length);//This give me the number of CP i.e. 2 

我想在這個格式的PS值(IIIIIIDIIIICPIIIIIIDIICPIIFIIII)

II, I,III,D,III,I,CP,III,I,I,I,D,II,CP,II,F,I,III 

,這樣我可以單獨指望他們像下面(或請建議更好的方法):

var arr = ps.split(","); 
var cp = $.inArray("CP",arr).length; //will output 2 
var Ist = $.inArray("I",arr).length;//will output 6 
var Snd = $.inArray("II",arr).length;//will output 3 
var Trd = $.inArray("III",arr).length;//will output 4 
var Dnt = $.inArray("D",arr).length;//will output 2 
var Fld = $.inArray("F",arr).length;//will output 1 

所以我的問題是:我怎麼能從我的表使用jQuery獲得像這樣的格式化數據II, I,III,D,III,I,CP,III,I,I,I,D,II,CP,II,F,I,III。我想分別在常規和私人狀態中查找CP位置的數量。請幫幫我。

+0

停止,使用PDO /庫MySQLi代替。而使用PHP短標籤可能會導致兼容性問題。儘量避免他們 – Raptor

+0

@Raptor,是的,請。我知道。但這不會幫助我,因爲我的問題只是jQuery,而不是PHP的一部分。 –

+1

@LalhriatpuiiMapuii發佈生成的HTML而不是服務器端代碼,因爲這個問題是關於jQuery/JS的。 – lshettyl

回答

1

你可以使用jQuery.map

var texts = $.map($('.ps'), function(el) { return $(el).text(); }); 
console.log(texts); 

輸出:["II", "I", "III", "D", "III", "CP"]

Fiddle

所以,如果您想根據以前.st行,你可以做的有數組:

var texts_private = $.map($('td.st:contains("Private") + td'), function (el) { 
    return $(el).text(); 
}); 
var texts_regular = $.map($('td.st:contains("Regular") + td'), function (el) { 
    return $(el).text(); 
}); 
console.log(texts_private, texts_regular); 

It將抓住.st行,看看裏面的文字是:contains()而不是看下一行。

的功能將讓你兩個數組:使用過時的`mysql_ *`功能

["I", "D", "CP"] ["II", "III", "III"] 

Fiddle

+0

謝謝你的嘗試。我如何分別獲得私人和正常身份的CP數量? –

+1

這會給你你想要的輸出,但不是常規/私人分開。你怎麼知道什麼是常規或私人? – putvande

+0

謝謝。從'td class =「st」',私人或常規狀態將由php代碼生成。所以'st.text()'會確定。請幫幫我。請看fiddlehttp://jsfiddle.net/4w7yeawx/1/ –