2016-05-16 40 views
0

Sup,我有使用jQuery获取data- *值的问题。jQuery无法获得data- *属性值,返回undefined

我的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); 
} 

但是控制台数收益不确定。最有趣的是,这段代码昨天正在工作,但今天它已经坏了。 有什么想法?

顺便说一句,我使用Bootstrap3和嫩枝

回答

2

两个小的变化需要:

1)只是通过this而不是this.id同时调用函数:

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

2)功能:

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

最后工程:)感谢的很多:)也许你知道为什么昨天这个代码工作,虽然有错误? –

+0

no pawel..dont有任何想法:) –

+0

好吧,没关系:)非常感谢您的帮助,抱歉,我没有足够的排名在这里为您的答案投票,所以+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); 

})