简体   繁体   中英

.attr() function isn't working

I know that this question has been asked and answered multiple times but the solutions i found isn't working for me.

this is the html element generated by php code :

<?php 

//here $index is a php variable and countIndex is my custom attribute

echo '<span class="glyphicon glyphicon-trash btnAction btnRemove tooltips" title="Remove" style="float:right" onclick="deleteData()" data-countIndex="'.$count.'"></span>';

?>

now when i click the span tag i want to alert it's custom attribute. And this is the code i used:

 function deleteData()
{
  alert( $( this ).data('countIndex') );

     // also tried these but didn't work
    // alert( jQuery( this ).attr( 'countIndex' ) );
   // alert( $( this ).attr( "class" ) );
}

I have verified it many times but i am not able to trace out the bug . Please find out the problem with my code.

I have added hard coded the value "11" for data-countIndex to show a demo

 function deleteData(elem){ console.log($(elem).attr("data-countIndex")) } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span onclick="deleteData(this)" data-countIndex="11"> test </span> 

Please try this

add "this"

onclick="deleteData(this)"

<span class="glyphicon glyphicon-trash btnAction btnRemove tooltips" title="Remove" style="float:right" onclick="deleteData(this)" data-countIndex="'.$count.'"></span>

function deleteData(elem){
    alert($(elem).attr("data-countIndex"))
}

What you want is $(this).attr('data-countIndex') . You access it by its full name just like any other attribute.

I believe that the reason $(this).data('countIndex') returns undefined is because data automatically un-camel-cases its argument . So it's actually looking for data-count-index instead of data-countIndex . If you had named your attribute data-count-index it would have worked.

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