[英]HTML5 Data-* attribute not working as expected
I have a page with an HTML5 doctype and I'm trying to use the data attribute in my table's <tr>
elements, like so: 我有一个HTML5文档类型的页面,我正在尝试在表格的
<tr>
元素中使用data属性,如下所示:
while($res = mysql_fetch_assoc($U)){
if($c == "table-row-dark"){
$c = "table-row-light";
}else{
$c = "table-row-dark";
}
echo "<tr data-id='".$res['rid']."' class='".$c."'>"
."<td>".$res['fname']." ".$res['lname']."</td>"
."<td>".$res['company']."</td>"
."<td>".$res['rcity'].", ".$res['rstate']."</td>"
."<td>".$res['rphone']."</td>"
."</tr>";
}
The following is my Javascript which adds an onclick listener to each row, then alerts the data-id
attribute's value. 以下是我的Javascript,它为每一行添加了一个onclick监听器,然后提醒
data-id
属性的值。
function addEvt(elem,eventType,handler){
if (elem.addEventListener){
elem.addEventListener (eventType,handler,false);
}
else if (elem.attachEvent){
elem.attachEvent ('on'+eventType,handler);
}
}
if(getElm('kickbacktbl')){
var kbRows = getElm('kickbacktbl').getElementsByTagName('tr');
var kbrcount = kbRows.length;
while(kbrcount--){
if(kbRows[kbrcount]){
var row = kbRows[kbrcount];
addEvt(row,"click",function(e){
cancelDefaultAction(e ? e:window.event);
var did = row.getAttribute('data-id');
var url = "kickback.php?id="+did;
window.alert(url);
//openShit(url);
return false;
});
}
}
}
The problem is, when url
is alerted , it shows the value of the attribute as null
. 问题是,当提示
url
时,它会将属性的值显示为null
。 What am I doing wrong? 我究竟做错了什么? How can I fix it while maintaining cross browser compatibility?
如何在保持跨浏览器兼容性的同时修复它?
Try to change row.getAttribute('data-id');
尝试更改
row.getAttribute('data-id');
to this.getAttribute('data-id');
to
this.getAttribute('data-id');
You are getting your elements by tagname and then you try to use a jquery function for them. 您通过标记名获取元素,然后尝试使用jquery函数。
this.getAttribute('data-id');
is the way to go. 是要走的路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.