JavaScript/jQuery - grabbing an integer from an element's id

前端 未结 10 536
青春惊慌失措
青春惊慌失措 2021-01-18 20:55

From the following markup.


      
10条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 21:33

    This should be the simplest way:

    var id = this.id.replace(/[^\d]/g,'')*1;
    

    It returns any digits from the ID attribute as a number (*1 does the conversion, similar to parseInt). In your example:

    $("#my-div a").click(function(){
        var n = this.id.replace(/[^\d]/g,'')*1;
        alert(n);  // alerts any number in the ID attribute
        alert(typeof n) // alerts 'number' (not 'string')
    });
    

提交回复
热议问题