简体   繁体   中英

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:

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.

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 . What am I doing wrong? How can I fix it while maintaining cross browser compatibility?

Try to change row.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.

this.getAttribute('data-id');

is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM