点击一个对象,获取另一个对象

Click on an object, get another object?

本文关键字:一个对象 获取      更新时间:2023-09-26

点击我得到一个对象的id。

id将是类似于'about-me'。

现在在点击函数中,我想要定位名为content-about-me的对象

我该怎么做?我试过了,但没有成功:

$('.sub-nav').on('click', function(){
        $('#content-'$(this).attr('id'));
    });

您必须将id与前缀content-:

连接起来
$('#content-' + this.id);

我还将$(this).attr('id')替换为等效但更短的this.id

请记住,与其这样做,不如将"other"元素的完整id存储在单击目标的某个地方。例如:

<div class="sub-nav" id="foo" data-other-element="content-foo">...</div>

然后做

$('.sub-nav').on('click', function(){
    var $other = $("#" + $(this).attr('data-other-element-'));
});

这段代码是DRY的,所以如果你决定改变id标签方案,你的JS代码也不需要改变。