0

From an open code I have this line

var average = parseFloat($(this).attr('id').split('_')[0]),

It gets the first part of a div id with '_' as delimiter. The problem is that an id cannot start with a number (naming violation convention). So I am going to add a letter before the id value in my php script. How do I insert substr(1) to this var to remove this letter and get 'average' as expected?

4

2 回答 2

2

Assuming you're talking about this format for an id:

<div id="A1000_bc"></div>

You can insert the substr(1) like this:

var average = parseFloat(this.id.split('_')[0].substr(1));

I might prefer to do it like this so it's a little less presumptious about the exact format and just grabs the first floating point numeric sequence:

var average = parseFloat(this.id.match(/[\d\.\+\-]+/)[0]);

Also, notice how I removed the jQuery. $(this).attr("id") performs a lot worse than this.id and offers no advantages here. jQuery should be used only when it's actually better than plain JS.

Both of these methods assume you are only going to present the code with properly formatted ids. If you want to handle a default condition when the id is not in the right format, then you will need multiple lines of code with some if conditions to check for validity and offer a default result when not valid.

Both options work here: http://jsfiddle.net/jfriend00/B4Rga/

Incidentally, if you control the HTML here, then there are better places to put data like this than in an id. I'd suggest a custom data attribute (HTML5 standard, but works everywhere).

<div id="whatever" data-avg="3.5"></div>

Then, you can get the data like this without having to parse it:

var average = parseFloat(this.getAttribute("data-avg"));
于 2012-04-12T01:41:01.070 回答
-3
var average = parseFloat(
        $(this)     // you've got a jQuery object here - bad place
        .attr('id') // you've got a string here - why not
        .split('_') // you've got an array here - bad idea
        [0]         // you've got a string here - why not
        // you need to have a number string here 
    );

记住:substr(1)只能在字符串上调用。

于 2012-04-12T01:42:09.967 回答