我有以下代码..我只想在表格的一列中添加按钮并在表格的一列中添加矩形。
var data = [{
"name": "a",
"section": 1,
"stars": "d1"
}, {
"name": "b",
"section": 2,
"stars": "d2"
}, {
"name": "c",
"section": 1,
"stars": "d3"
}];
var columns = ['name', 'section', 'stars']
// create table
var table = d3.select("#table").append("table");
var thead = table.append("thead").append("tr");
thead.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(d) {
return d;
});
var tbody = table.append("tbody");
thead.append("th").text('Action');
data.forEach(function(d, i) {
trow = tbody.append("tr")
trow.selectAll("td")
.data(columns)
.enter()
.append("td")
.text(function(e) {
return d[e]
});
trow.selectAll("td.button")
//use a class so you don't re-select the existing <td> elements
.data(function(d) {
return [d];
})
.enter()
.append("td")
.attr("class", "button")
.append("button")
.text(function(d) {
return "ADD"
})
.on("click", function(d) {
console.log(d);
alert("particular row data" + JSON.stringify(d))
});
});
div {
height: 250px;
width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="table"></div>
如何在部分列中添加按钮以及如何在星号列中插入矩形。
最佳答案
希望您在以下代码片段中寻找类似的输出。
var data = [{
"name": "a",
"section": 1,
"stars": "d1"
}, {
"name": "b",
"section": 2,
"stars": "d2"
}, {
"name": "c",
"section": 1,
"stars": "d3"
}];
var columns = ['name', 'section', 'stars']
// create table
var table = d3.select("#table").append("table");
var thead = table.append("thead").append("tr");
thead.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(d) {
return d;
});
var tbody = table.append("tbody");
thead.append("th").text('Action');
data.forEach(function(d, i) {
trow = tbody.append("tr");
trow.append("td")
.text(d["name"]);
trow.append("td")
.attr("class", "button")
.append("button")
.text("ADD")
.on("click", function() {
alert("particular row data" + JSON.stringify(d))
});
var svg = trow.append("td")
.append("svg")
.attr("width",30)
.attr("height",20);
svg.append("rect")
.attr("x",0)
.attr("y",0)
.attr("width",30)
.attr("height",20)
.style("stroke","red")
.style("fill","black");
svg.append("text")
.attr("x",15)
.attr("dy",10)
.text(d["stars"])
.attr("text-anchor","middle")
.style("stroke","white")
.style("alignment-baseline","central");
});
div {
height: 250px;
width: 500px;;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="table"></div>
关于javascript - 如何使用 d3 为表中的特定列设置按钮和矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610739/