如何获得colspan的价值
我尝试了不同的jQuery方法:
var num = $(this).attr('colspan').text(); var num = $(this).attr('colspan').val(); var num = $(this).('td[colspan]').val(); var num = $(this).('td[colspan]').text(); var num = $(this).('td[colspan]').attr('id');
这来自W3Schools: var num = document.getElementById($(this)).colSpan;
没运气。 它在我的console.log()
是未定义的或未被捕获的TypeError
编辑:我已经尝试了你的建议,它仍然无法正常工作。 以下是上下文中代码的一部分:
$('table td').on('mouseenter mouseleave', function(e){ var th, index, id, td; if(e.type === 'mouseenter'){ id = $(this).attr('id'); td = $(this); var num = $(this).attr('colspan'); console.log("td = "+td+" colspan = "+num); td.addClass('highlight'); var $table_body_scroll=$('table.body_scroll'), header_table=$( '
' ), scroll_div=''; var $targetHeaderTable=$("table.header_table").eq(index); $('thead tr th').each(function() { console.log("th = "+$(this).text()); console.log("id = "+id); if ($(this).text() == id) { var num = td.attr('colspan'); //console.log("td = "+td+" colspan = "+num); $(this).addClass('highlight'); } }); index = $('td').index($(e.target)); $(e.target).prevAll().addClass('highlight'); }else{ $('.highlight').removeClass('highlight'); } });
和我的控制台日志: td = [object Object] colspan = undefined
使用prop
获取属性/属性的值集,这将反映页面加载后使用JS对属性所做的任何更改:
$(this).prop("colSpan");
JS Fiddle: http : //jsfiddle.net/9u8L2/1
如果this
指的是td元素那么
var span = $(this).prop('colSpan')//or var span = $(this).attr('colspan')