.attr()函数不起作用

时间:2015-07-12 07:34:43

标签: php jquery

我知道这个问题已被多次询问和回答,但我找到的解决方案并不适用于我。

这是由php代码生成的html元素:

<?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>';

?>

现在当我点击span标签时,我想提醒它的自定义属性。这是我使用的代码:

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

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

我已多次验证,但我无法找出错误。请查看我的代码的问题。

2 个答案:

答案 0 :(得分:0)

我已为data-countIndex添加了&#34; 11&#34; 的硬编码以显示演示

&#13;
&#13;
function deleteData(elem){
  console.log($(elem).attr("data-countIndex"))
}
&#13;
<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>
&#13;
&#13;
&#13;

请尝试此

添加&#34;此&#34;

<强>的onclick =&#34; deleteData(本)&#34;

<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"))
}

答案 1 :(得分:0)

你想要的是using myProject.Helpers; // And somewhere in your classes var sha = CommonFunctions.GenerateSHA("Your String"); 。您可以使用其全名来访问它,就像任何其他属性一样。

我认为$(this).attr('data-countIndex')返回$(this).data('countIndex')的原因是因为undefined automatically un-camel-cases its argument。因此,它实际上在寻找data而不是data-count-index。如果您已将属性命名为data-countIndex,那么它就会起作用。

相关问题