我有以下代码:
<li class="shop-currencies">
<a href="#" id="EUR" data-currency="EUR">€</a>
<a href="#" id="GBP" data-currency="GBP">£</a>
<a href="#" id="USD" data-currency="USD">$</a>
<a href="#" id="ZAR" data-currency="ZAR" class="current">R</a>
</li>
单击项目时,我想将类设置为单击的项目并获取单击的项目的 ID。这是我目前所拥有的:
$('.shop-currencies').click(function() {
var id = $(this).attr('id');
alert(id);
/**
* Remove the classes from the currency elements
*/
$('.shop-currencies').find('a').each(function(e) {
$(this).removeClass();
});
/**
* Set the class of the clicked element
*/
$( '#' + id).addClass('current');
});
返回的 ID 为“未定义”如何获取点击链接的 ID?
谢谢
最佳答案
您需要将点击处理程序附加到子 anchor 元素:
$('.shop-currencies a').click(function() {
var id = $(this).attr('id');
alert(id);
/**
* Remove the classes from the currency elements
*/
$('.shop-currencies').find('a').not(this).removeClass('smclass')
/**
* Add class to current elements
*/
$(this).addClass('smclass')
});
关于javascript - Jquery - 如何获取列表项中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28027362/