javascript - Jquery - 如何获取列表项中的元素

标签 javascript jquery

我有以下代码:

                <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/

相关文章:

jquery - 在 jquery 中创建的 <a> 标签

javascript - 有没有办法在addEventListener中使用js写的html?

javascript - 创建根(...): Target container is not a DOM element in React Test file

javascript - 编译时设置错误 react native "gradle"

php - 使用node.js Node http服务器而不是php/ruby​​/etc + nginx有什么优势?

javascript - 如何在用户不访问该页面的情况下将项目添加到 Chrome 缓存?

jQuery.Deferred()/GWT 中的 Promises 功能?

javascript - jQuery 哪个是正确的函数定义?

javascript - jQuery 使用字符串在对象中搜索

jquery - 单击文档时隐藏,单击 div 时除外