我有这段代码,我需要对前两个对象做一些事情,然后对其余的对象做一些其他的事情,但是怎么做呢?
我从<tr data-name='test' data-price='2' data-one='blabla' ...
获取数据
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>";
最佳答案
你不能真正依赖属性的顺序。如果您可以更改标记,我建议您使用 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 })
)
);
如果不是这样,至少选择比one
、two
等更好的名字——这样做会让你自己变得尽可能困难。
根据评论中阐明的您的具体情况,我会这样做:
<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 })
);
})
);
关于javascript - 对于每个函数。先对 2 做一些事情,然后再对其余的做其他事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19990804/