jQuery无法获取data- *属性值,返回undefined

时间:2016-05-16 11:27:12

标签: javascript php jquery html twig

Sup,我在使用jQuery获取data- *值时遇到问题。

我的HTML代码是:

<button type="button" 
   class="btn btn-danger"
   id="{{ currency.id }}"
   data-curname="{{ currency.name }}"
   data-toggle="modal"
   data-target="#deleteConfirm"
   onclick="deleteCurConf(this.id)">
   <span class="glyphicon glyphicon-remove"></span>
   &nbsp;Delete
 </button>

jQuery是:

function deleteCurConf(id) {
 var curName = $('#' + id).data('curname');
 console.log(curName);
}

但是控制台日志返回undefined。最有趣的是这个代码昨天正在运行,但今天已经破了。  有什么想法吗?

顺便说一句,我正在使用Bootstrap3和Twig

2 个答案:

答案 0 :(得分:2)

需要做两点改动:

1)在调用函数时只需传递user_verificationcode而不是SELECT t1.* FROM Userregistration AS t1 JOIN ( SELECT user_id FROM user_verificationcode WHERE codetype IN ('mobile', 'email') GROUP BY user_id HAVING COUNT(DISTINCT codetype) = 2 AND SUM(status <> 1) = 0 ) AS t2 ON t1.id = t2.user_id

this

2)功能:

this.id

答案 1 :(得分:0)

jQuery中更清洁的方法是:

   <button type="button" 
   class="btn btn-danger handleClick"  // Added extra class
   id="{{ currency.id }}"
   data-curname="{{ currency.name }}"
   data-toggle="modal"
   data-target="#deleteConfirm"       
   <span class="glyphicon glyphicon-remove"></span>
   &nbsp;Delete
 </button>

<强>的jQuery

$("document").on("click",".handleClick",function(evnt){

 var curName = $(evnt.target).data('curname'); // use $(id)
 console.log(curName);

})