5

ユーザーがポップアップウィンドウの幅と高さの値を入力するフォームを作成しました。そのために使っwindow.openています。

したがって、幅と高さの値が整数かどうかを確認する必要があると思います。変数が整数であることを確認する関数があります...

function isInteger(possibleInteger) {
    return !isNaN(parseInt(possibleInteger));
}

しかし、この関数を幅と高さの関数に呼び出して、ユーザーが整数を入力したかどうかを確認する方法がわかりません。誰でも助けることができますか?

4

3 に答える 3

6

This is an answer to question mentioned in the topic, not the actual one in the body of the text :).

The following method is more accurate on determining if the string is a real integer.

function isInteger(possibleInteger) {
    return /^[\d]+$/.test(possibleInteger)​;
}

Your current method validates "7.5" for instance.

EDIT: Based on machineghost's comment, I fixed the function to correctly handle arrays. The new function is as follows:

function isInteger(possibleInteger) {
        return Object.prototype.toString.call(possibleInteger) !== "[object Array]" && /^[\d]+$/.test(possibleInteger);
}
于 2010-09-05T10:50:00.930 に答える
4

パフォーマンスが心配な場合の代替回答。

var isInteger1 = function(a) {
    return ((typeof a !== 'number') || (a % 1 !== 0)) ? false : true;
};

Chrome での Zafer の回答と比較した負荷テストの結果:

undefined => 4ms vs 151ms
1 => 10ms vs 390ms
1.1 => 61ms vs 250ms
'1' => 8ms vs 334ms
[1] => 9ms vs 210ms
{foo: 'bar'} => 8ms vs 478ms

自分の目で確かめてください: jsfiddle

于 2013-04-29T17:05:31.857 に答える
1
var isWidthAnInteger = isInteger(document.getElementById('width').value);
var isHeightAnInteger = isInteger(document.getElementById('height').value);
if (isWidthAnInteger && isHeightAnInteger) {
    // TODO: window.open
}

次のテキストボックスがある場所:

Width: <input type="text" id="width" name="width" />
Height: <input type="text" id="height" name="height" />
于 2010-09-05T09:06:18.223 に答える