doujie7346 2015-07-12 07:34
浏览 140
已采纳

.attr()函数不起作用

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.

  • 写回答

2条回答 默认 最新

  • douyou2048 2015-07-12 07:39
    关注

    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"))
    }
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题