我有一张包含动态生成内容的表格。每行都有一个按钮,用于为该行提供服务。在我的情况下,我希望我的按钮的outerHTML在其行上采用名称的名称。
我无法将this
分配给我的onclick事件。按原样,单击任一按钮将仅重复第一行上的名称。我不确定使按钮更改为适当的行名称的正确语法。
var erray = ["Todd", "Bill", "Sam"];
var pname = document.querySelectorAll('.pname');
var adoptname = document.querySelectorAll('.adoptname');
for (var i = 0; i < erray.length; i++){
var adoptname = document.querySelectorAll('.adoptname');
pname[i].innerText = erray[i];
adoptname[i].onclick = adoption;
function adoption(){
for (var i = 0; i < pname.length; i++)
this.outerHTML = pname[i].innerHTML;
}
}
&#13;
table { border: 1px solid black; }
&#13;
<table>
<thead><tr>
<th>Name</th>
<th>Adopt</th>
</tr></thead>
<tbody>
<tr><td class="pname"></td><td><button class="adoptname">Adopt</button></td></tr>
<tr><td class="pname"></td><td><button class="adoptname">Adopt</button></td></tr>
</tbody>
</table>
&#13;
答案 0 :(得分:2)
考虑你的HTML是这样的;
<table>
<thead>
<th>Name</th>
<th>Adopt</th>
</thead>
<tbody id="table_body">
</tbody>
</table>
现在看看js
var array=["Todd","Bill","Sam"];
var html="";
for(var i=0;i<array.length;i++)
{
html=html+"<tr><td>"+array[i]+"</td><td><button id=\"adopt-"+array[i]+"\">Adopt</button>";
}
$("#table_body").html(html);
现在看一下点击事件;
$("#table_body").on("click","[id^=adopt]",function(){
var id=$(this).attr("id");
var name=id.split("-")[1];
alert(name);
})
答案 1 :(得分:1)
<table>
<thead><tr>
<th>Name</th>
<th>Adopt</th>
</tr></thead>
<tbody id="table_body">
<tr><td class="pname"></td><td><button class="adoptname">Adopt</button></td></tr>
<tr><td class="pname"></td><td><button class="adoptname">Adopt</button></td></tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
window.onload=function()
{
var array=["Todd","Bill","Sam"];
for(var i=0;i<array.length;i++)
{
$("#table_body tr:nth-child("+(i+1)+") .pname").html(array[i]);
$("#table_body tr:nth-child("+(i+1)+") .adoptname").attr("id","adopt-"+array[i]);
}
$("#table_body").on("click","[id^=adopt]",function(){
var id=$(this).attr("id");
var name=id.split("-")[1];
alert(name);
});
}
</script>