2012-07-17 21 views
0

請參閱下面我的代碼:jQuery的發現列類

 <div class="grid_6 box a col1 row1" style="left: 231px; top: 380px; position: absolute; "></div> 
    <div class="grid_6 box a col2 row1" style="left: 471px; top: 380px; position: absolute; "></div> 
    <div class="grid_6 box a col3 row1" style="left: 711px; top: 380px; position: absolute; "></div> 
    <div class="grid_6 box a col4 row1" style="left: 951px; top: 380px; position: absolute; "></div> 
    <div class="grid_6 box b col1 row2" style="left: 231px; top: 540px; position: absolute; "></div> 
    <div class="grid_6 box b col2 row2" style="left: 471px; top: 540px; position: absolute; "></div> 
    <div class="grid_6 box b col3 row2" style="left: 711px; top: 540px; position: absolute; "></div> 
    <div class="grid_6 box b col4 row2" style="left: 951px; top: 540px; position: absolute; "></div> 

我需要做一個jQuery腳本將找出哪些山口和行我已經點擊。

這可以輕鬆完成嗎?

+0

鑑於什麼?當你點擊一個特定的單元格時? – ptrn 2012-07-17 22:46:07

+0

對不起,應該提到這一點。 – 2012-07-17 22:46:30

+0

然後只要檢查div有什麼樣的類,然後查找col *和row *,那會得到你想要的。 – TheZ 2012-07-17 22:49:12

回答

2

假設你的點擊處理程序是在div ...

var col_row = this.className.match(/col(\d+)\s+row(\d+)/); 

列將在指數1,行索引2

var col = col_row[1], 
    row = col_row[2]; 

FWIW,你冷在Firefox做到這一點...

var [_, col, row] = this.className.match(/col(\d+)\s+row(\d+)/) 
+1

是我所需要的。 – 2012-07-17 22:54:32

+1

+1,模式匹配處於最佳狀態。 ) – raina77ow 2012-07-17 22:55:36

+0

編程時我是一個noob。 – 2012-07-17 22:57:44

0

我建議使用data-屬性,因爲它會更容易得到你想要的確切數據。但是,讓你的類:

$('DIV').click(function(evnt){ 
    alert($(this).attr('class')); 
});​ 
1

我張貼的jsfiddle的解決方案在此地址:http://jsfiddle.net/6GBPF/3/

正如你看到的,代碼非常簡單,使用一些基本的正則表達式。 (^|[^\w])row([0-9]+)基本上的含義是:在字符串row前面加上一個或多個數字的序列,後面跟一個不是單詞字符或字符串開頭的字符(在本例中爲類屬性),以便行[0-9 ] +類甚至可以在屬性的開始處。從match函數的數組結果中,最後一個元素是您正在查找的元素。 該列的工作方式相同。

$(document).ready(function(){ 
    $('.grid6').on('click', function(){ 
     var $div = $(this), 
      rowMatch = $div.attr('class').match("(^|[^\w])row([0-9]+)"), 
      row = rowMatch[rowMatch.length -1], 
      colMatch = $div.attr('class').match("(^|[^\w])col([0-9]+)"), 
      col = colMatch[colMatch.length -1]; 
     alert("row: " + row + " - col: " + col); 
    }); 
}); 

鑑於這一事實,我不知道,如果你生成你的工作並不能確保類屬性始終具有相同類的標記,正則表達式的作品,即使在情況你有這樣的類屬性:not_a_row1 row2(正則表達式採用第二個(正確的)),每個順序。

發佈的其他解決方案(var col_row = this.className.match(/col(\d+)\s+row(\d+)/);)假定class屬性始終具有該確切結構。即使不那麼謹慎,如果你能確定,那是一個非常簡潔和富有表現力的解決方案。