How to slice a id and grab a number?

不想你离开。 提交于 2019-12-11 18:35:02

问题


I have a jQuery id like

<div id="myid-page-top-0">
    some stuff
</div>

I want to use jQuery to grab the "0" from the end of the #id. I have tried like

$('div').slice(-1,0);

But this doesn't work ? Any ideas ?


回答1:


Instead of slice, which would only work if your id contains numbers 0-9, not if it is say 10 or 11, you should base it off of the dashes.

Something like:

var id = "myid-page-top-0";
alert(id.split("-")[3]);

or in your code something like:

var number = $('div').attr('id').split("-")[3];



回答2:


$('div') is an object, you want the ID:

$('div').attr('id').slice(-1,0);

If your numbers go into double digits though you might run into problems, it might be better to do it like this:

$('div').attr('id').replace('myid-page-top-', '');



回答3:


Here you go buddy. Tested and working. iterates through all divs and returns the ending number

<script type="text/javascript">
 $(document).ready(function() {

                            $('div').each(function(i) {
                                                   var id = $(this).attr("id");

                                var slices = id.substr(id.length - 1, 1); 
                                alert(slices);
                                });
                            }
                            );
  </script>


<div id="myid-page-top-0">
    some stuff
</div>

<div id="myid-page-top-1">
    some stuff
</div>

<div id="myid-page-top-2">
    some stuff
</div>


来源:https://stackoverflow.com/questions/7771197/how-to-slice-a-id-and-grab-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!