简体   繁体   English

parseInt()错误:参数无效

[英]parseInt() error: invalid argument

I get a javascript error "invalid arguement" when I use parseInt(). 使用parseInt()时出现JavaScript错误“无效争论”。 What am i doing wrong? 我究竟做错了什么?

The function is to increase the font size of every element on a frame by 1 该功能是将框架上每个元素的字体大小增加1

<script>
   var sizeCounter = 1;
    function changeFontSize(){
        //var elements = parent.main.document.getElementsByTagName
        var myElements = parent.main.document.getElementsByTagName('*')

        for (i=0;i<myElements.length;i++){
                if(myElements[i].style.fontSize != null){       
                        var elmFontSize = myElements[i].style.fontSize + "";
                        elmFontSize.replace("px","");

                        if(elmFontSize != "") {
                            var elmFontSizeNum = parseInt(elmFontSize);

                        }
                            var resultSize = elmFontSizeNum + sizeCounter;

                            myElements[i].style.fontSize = resultSize + "px";


                        //alert(myElements[i].className)
                    }
                    sizeCounter++;
            }
    }


</script>

There's a lot wrong. 有很多错 Here's a suggestion for simplifying/rewriting your function: 这是简化/重写函数的建议:

function changeFontSize(sizeCounter){
 sizeCounter = sizeCounter || 1;
 var myElements = document.getElementsByTagName('*'), currentFontSize = 0;
 for (i=0;i<myElements.length;i++){
  var fsNow = getStyle(myElements[i],'font-size');
  if (fsNow){
   currentFontSize = Number(fsNow.replace(/[^\d]/g,''));
   myElements[i].style.fontSize = (currentFontSize + sizeCounter) + 'px';
  }
 }
}

Where getStyle is: 其中的getStyle是:

function getStyle(el,styleProp)
{
  el = /string/i.test(typeof el) ? document.getElementById(el) : el;
  if (!el){return null;}
  var result;
  if (el.currentStyle){
    return el.currentStyle[styleProp];
  }
  else if (window.getComputedStyle){
    return document.defaultView.getComputedStyle(el,null)
           .getPropertyValue(styleProp);
  }
  return null;
}

See this jsfiddle 看到这个jsfiddle

parseInt takes a string as first parameter, you may want to make sure that elmFontSize is actually a string using typeof(elmFontSize) . parseInt将字符串作为第一个参数,您可能需要使用typeof(elmFontSize)来确保elmFontSize实际上是字符串。 If it's not a string, you can transform it into a string before calling the parseInt function. 如果不是字符串,则可以在调用parseInt函数之前将其转换为字符串。

You only handle "px" and fontsize isn't necessarily a "px" value. 您只能处理“ px”,而fontsize不一定是“ px”值。 If it is for example "em" then parseInt will fail because it is trying to convert a non number value. 例如,如果它是“ em”,则parseInt将失败,因为它试图转换非数字值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM