我不明白为什么在尝试从下面的代码中console.out iUsedId变量时,我得不到定义。
在这里,我将用户id附加到data-iUserId。
var aUsers = [];            
            for( var i = 0; i < aUsers.length; i++ ){
                $("#lblUsers").append('<tr><th scope="row">'+aUsers[i].id+'</th><td>'+aUsers[i].username+'</td><td>'+aUsers[i].firstName+'</td><td>'+aUsers[i].lastName+'</td><td>'+aUsers[i].email+'</td><td>'+"<span data-iUserId='"+aUsers[i].id+"'</span><input type='checkbox' id='chk_"+i+"'"+'</td></tr>');
            }在这里,我尝试使用data属性中的数据,但在控制台中,我得到的都是undefined。
$(document).ready(function() {
    $("#remove").on("click", function() {
        $('input:checked').each(function() {
            $(this).closest('tr').remove();
            var iUserId = $(this).attr('data-iUserId');
            console.log(iUserId);
            for (var i = 0; i < aUsers.length; i++) {
                if (iUserId == aUsers[i].iUsersId) {
                    aUsers.splice(i, 1);
                }
            }
        });
    });
});有什么疑问吗?请帮帮我!
发布于 2016-09-01 00:55:21
原因是您循环遍历的是复选框,而不是具有您试图访问的属性的span。
$(this)指的是复选框,而不是您正在使用的each方法中的跨度:
 $('input:checked').each(function() { 
     // Inside this each statement $(this) refers 
     // to the the current 'input:checked' element being accessed
 });您应该将data-iUserId属性放在复选框中,因为您正在访问该元素。
还有!您缺少开始span标记上的结束'>‘:
<span data-iUserId='"+aUsers[i].id+"'</span>发布于 2016-09-01 00:55:54
您正在删除包含容器的父元素,然后尝试访问该元素。
删除父级应该是最后一步:
$(document).ready(function() {
    $("#remove").on("click", function() {
        $('input:checked').each(function() {
            var iUserId = $(this).closest('span').attr('data-iUserId');
            console.log(iUserId);
            for (var i = 0; i < aUsers.length; i++) {
                if (iUserId == aUsers[i].iUsersId) {
                    aUsers.splice(i, 1);
                }
            }
            $(this).closest('tr').remove();
        });
    });
});另外,请考虑@pBuch的注释
发布于 2016-09-01 01:28:25
var aUsers = [];
//...somehow populate array...
// We have to assume here that the array got populated 
for (var i = 0; i < aUsers.length; i++) {
  $("#lblUsers").append('<tr><th scope="row">' + aUsers[i].id + '</th><td>' + aUsers[i].username + '</td><td>' + aUsers[i].firstName + '</td><td>' + aUsers[i].lastName + '</td><td>' + aUsers[i].email + '</td><td>' + "<span data-iUserId='" + aUsers[i].id + "'></span><input type='checkbox' id='chk_" + i + "'" + '</td></tr>');
}
$(document).ready(function() {
  $("#remove").on("click", function() {
    $("#lblUsers").find('input[type="checkbox"]:checked').each(function() {
      // fixed to get the element with the data
      var iUserId = $(this).siblings('[data-iUserId]').data('iuserid');
      console.log(iUserId);
      for (var i = 0; i < aUsers.length; i++) {
        // bad practice to use a global aUsers
        if (iUserId == aUsers[i].iUsersId) {
          aUsers.splice(i, 1);
        }
      }
      $(this).closest('tr').remove();
    });
  });
});https://stackoverflow.com/questions/39254992
复制相似问题