单击时,在动态表的td内获取span的id

时间:2017-07-26 11:45:01

标签: jquery html html-table onclick

我试图获取在表格中动态创建的范围的ID。我创建了这样的表:

var initTable = function () {
$.getJSON(jsonFile, function (data) {
    var items = [];
    $.each(data, function (key, val) {
        var spanid = val.key;
        items.push(
            '<tr><td>' + val.label + '</td>'
            + '<td><span class="parameters" id="' + spanid + '">---</span> ' + val.value + '</td></tr>'
            );
        });
        $("#myTable tbody").html(items.join(""));
    });
};

当我点击td时,我需要得到跨度的id。我的查询是这样的:

$("#myTable span").click(function () {

    var id = $(this).attr("id");
    alert(a);
});

它不起作用。有人知道为什么?

谢谢

6 个答案:

答案 0 :(得分:1)

我的帮助

&#13;
&#13;
table {border: solid 1px #ccc; border-collapse: collapse;}
table td {border: solid 1px #ccc;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
	<tr>
		<td><span id="1">Span 1</span></td>
		<td><span id="2">Span 2</span></td>
		<td><span id="3">Span 3</span></td>
		<td><span id="4">Span 4</span></td>
	</tr>
</table>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这个怎么样:

我正在使用逆转方式。我希望它能为你充实。

&#13;
&#13;
$(document).ready(function(){

$('span').click(function(){
   if($(this).closest("table").attr("id") == "MyTable" )
   alert($(this).attr("id"));
});

});
&#13;
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
  </script>

<table id="MyTable">
<tbody>
<tr><td>Hello</td>'</tr>
<tr><td><span id ="inTable" style="cursor:pointer;">Span Inside Table</span></td></tr>
</tbody>
</table>
<span id="outTable" style="cursor:pointer;">
  span Outside Table
</span>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试这个。

$("#myTable tbody tr td span").click(function () {

    var id = $(this).attr("id");
    alert(id);
});

现在纠正了...我不是要给整个节目。这只是上面代码所面临的问题的提示和识别

答案 3 :(得分:0)

这是因为你在错误的变量上做警报

您的代码中

a undefined

试试这个

$(document).on('click',"#myTable span",function () {
    var id = $(this).attr("id");
    alert(id);
});

答案 4 :(得分:0)

为什么不在.parameter元素中尝试<span>课程?并记得使用单引号。

$('.parameters').click(function () {
       var id = $(this).attr('id');
       alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="#myTable">
  <tr>
  <td>item</td>
  <td><span style="cursor:pointer" class="parameters" id="0001">---</span>Value1</td>
  </tr>
  
  <tr>
  <td>item 2</td>
  <td><span style="cursor:pointer" class="parameters" id="0002">---</span>Value2</td>
  </tr>
</table>

答案 5 :(得分:-1)

尝试.live()或on()方法

$("#myTable span").on( "click", function() {
        var id = $(this).attr("id");
        alert(id);
    });

我还没有运行此代码,但我知道这是问题所在。

相关问题