2013-11-14 81 views
0

我有這段代碼,我需要對前2個項目做些事情,然後再做其他事情,但是怎麼做? 我從<tr data-name='test' data-price='2' data-one='blabla' ...對於每個功能。先做2件事,然後做其他事情?

data = $(this).data(); 
html_option = "<table id='Unit_Options_Table'>"; 
// Do some thing with the first 2 
$.each(data, function(option, cost) { // Then do something with the rest 
    html_option += "<tr>" + 
      "<td class='Unit_Options_Name_td'>" + option + "</td>" + 
      "<td class='Unit_Options_Cost_td'>" + cost + "</td>" + 
      "</tr>"; 
}); 

html_option += "</table>"; 
+0

'each',正如其名稱中明確規定,不帶*每個*元素的東西。所以你顯然不能在這裏使用它。 –

+0

你在循環一個數組還是一個對象? – bfavaretto

+0

@bfavaretto數據是jQuery節點對象的數組 - 它在其代碼的第一行中定義。 –

回答

2

你真的不能依靠屬性的順序上。如果你可以改變的標記,我推薦使用JSON爲你的價值觀:

<tr data-name="test" data-price="2" data-items='["blabla",…]'> 
var name = this.dataset.name; 
var cost = this.dataset.price; 
var items = JSON.parse(this.dataset.items); 

var option = $("<table>", { id: "Unit_Options_Table" }); 

// I’m not even sure where the loop belongs here 
option.append(
    $("<tr>").append(
     $("<td>", { class: "name", text: name }), 
     $("<td>", { class: "cost", text: cost }) 
    ) 
); 

如果沒有,至少挑選更好的名字比onetwo,等等 - 你讓這樣做對你來說盡可能地難。

在您的具體情況爲在評論中澄清,我應該這樣做:

<tr data-name="bla" data-cost="3" data-items='[{"name":"test","cost":20},…]'> 
var data = $(this).data(); 
var items = $.parseJSON(data.items); 

var option = 
    $("<table>", { id: "Unit_Options_Table" }) 
     .append(
      $("<tr>").append(
       $("<th>", { text: data.name }), 
       $("<th>", { text: data.cost }) 
      ) 
     ) 
     .append(
      $.map(items, function(item) { 
       return $("<tr>").append(
        $("<td>", { text: item.name }), 
        $("<td>", { text: item.cost }) 
       ); 
      }) 
     ); 
+0

我可以控制的外觀。 數據名稱和數據成本是「標題」,然後是我得到了一些數據對,如「data-oneName&data-oneCost」。 使用你的eksample我會如何配對你的? –

+0

@DennisSødalChristensen:我添加了一個具體的例子 - 試試看。 – rninty

+0

試圖讓它工作,但從jQuery得到一個錯誤: 未捕獲SyntaxError:意外的令牌ü 我在這裏做了一個小測試腳本,你可以看到什麼是錯的? http:// pastebin。com/96YUWpv1 –

1

獲取數據時,請勿使用.each,你會發現它容易得多。

doSomething(data[0], data[1]); 
for (var i = 2; i < data.length; ++i) { 
    doSomethingElse(data[i]); 
} 

強迫自己使用一個方便的功能是不是很方便?

+0

請注意,與for循環不同,jQuery的每種方法都會迭代各種東西! – adeneo

0

Shouldn't

option 

來,如果你遍歷指數數組 ?

所以應該這麼簡單

$.each(data, function(option, cost) { 
    if(option < 2){ 
    //do something with first two 
    }else{ 
    html_option += "<tr>" + 
      "<td class='Unit_Options_Name_td'>" + option + "</td>" + 
      "<td class='Unit_Options_Cost_td'>" + cost + "</td>" + 
      "</tr>"; 
} 
}); 
相關問題