最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get last character from id attribute - Stack Overflow

programmeradmin2浏览0评论

I need to get the last character of the id of an element and use it in order to find another element by id in the same page.

What I've tried so far:

$(".spoilerButton").each(function(){
        $currentId=($this).attr("id").slice(-1);
        $hiddenContent=$("#spoiler"+$currentId);
        $this.click(function(){
                $hiddenContent.toggle(500);
        });
});

Basically, every element of class spoilerButton with an id of spoilerButtonN where N an integer, has a corresponding element with id spoilerN that needs to show/hide, once it is clicked.

The code does not seem to run the $currentId=($this).attr("id").slice(-1); part, where I try to get the last character (N) from the spoilerButton's id.

What is the correct way to do it?

I need to get the last character of the id of an element and use it in order to find another element by id in the same page.

What I've tried so far:

$(".spoilerButton").each(function(){
        $currentId=($this).attr("id").slice(-1);
        $hiddenContent=$("#spoiler"+$currentId);
        $this.click(function(){
                $hiddenContent.toggle(500);
        });
});

Basically, every element of class spoilerButton with an id of spoilerButtonN where N an integer, has a corresponding element with id spoilerN that needs to show/hide, once it is clicked.

The code does not seem to run the $currentId=($this).attr("id").slice(-1); part, where I try to get the last character (N) from the spoilerButton's id.

What is the correct way to do it?

Share Improve this question asked May 7, 2014 at 17:13 hytromohytromo 1,5312 gold badges29 silver badges57 bronze badges 4
  • You don't seem to define $this. And it would be simpler to do ̀this.id.slice(-1) – Denys Séguret Commented May 7, 2014 at 17:14
  • 1 I don't think it's generally a remended practice to prefix all your variable names with $. – JLRishe Commented May 7, 2014 at 17:15
  • Right. If there's any convention, it's that $var should be a variable containing a jQuery object, e.g. $this = $(this). – Barmar Commented Jun 10, 2014 at 17:53
  • You should also declare local variables with var. You're setting global variables $currentId and $hiddenContent, which is not desirable. – Barmar Commented Jun 10, 2014 at 17:54
Add a ment  | 

1 Answer 1

Reset to default 15

You have your parens in the wrong place:

$currentId=$(this).attr("id").slice(-1);
// Note     ^    ^

Or of course, specifically with respect to the id attribute, $(this).attr("id") is just a long way to write this.id, so:

$currentId=this.id.slice(-1);

...but that's not true for all attributes, just certain reflected ones like id.

发布评论

评论列表(0)

  1. 暂无评论