【问题标题】:Select an element whose id matches href attribute jQuery [duplicate]选择一个id匹配href属性jQuery的元素[重复]
【发布时间】:2016-07-09 18:12:31
【问题描述】:

我想选择一个元素,其id<a> 元素的href 匹配

HTML

<a href="web"></a>
<a href="app"></a>

<div id="web"></div>
<div id="app"></div>

jQuery

$('a').on('click', function(e) {
   e.preventDefault();
   var $href = $(this).attr('href');
   var $id = $('div').attr('id');
   $(this).addClass('active');
   //HERE I WANT TO SELECT THE DIV WHOSE "id" MATCHES THE "href" of the <a> clicked 
   $('div').id($href).addClass('active');
});

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    $href 中添加前导# 以获取div 的选择器,如下所示。

    $('a').on('click', function (e) {
        e.preventDefault();
        var $href = $(this).attr('href');
        $(this).addClass('active');
    
        $('#' + $href).addClass('active'); // this is what you need to do
    });
    

    【讨论】:

    • 就是这样!问题是,$('#' + $href) 是做什么的?
    • $('#' + $href) 选择id与点击的&lt;a&gt;href相同的div。 @tavozapata
    • 哦,我知道了,我从来没有想过加号会这样做
    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2012-01-12
    • 2010-12-04
    • 1970-01-01
    • 2016-01-05
    • 2011-11-09
    • 1970-01-01
    • 2015-06-07
    相关资源
    最近更新 更多