1. 程式人生 > >js程式碼中 何時加入引號,何時不加

js程式碼中 何時加入引號,何時不加

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>函式傳參</title>  
    </head>
    <style type="text/css">
        #div1{
            width: 200px;
            height: 200px;
            border: red solid 2px;
            background-color
: red
; background-size:cover ; }
</style> <script type="text/javascript"> function set(set1,set2){ var js_1=document.getElementById('div1'); js_1.style[set1]=set2; } </script> <body> <input
type="button" value="變綠" onclick="set('backgroundColor','green')" />
<input type="button" value="變寬" onclick="set('width','400px')" /> <input type="button" value="變高" onclick="set('height','400px')" /> <input type="button" value="向右" onclick="set('margin-left','200px')"
/>
<div id="div1"> </div> </body> </html>

先注意下 單雙引號的位置

  1. 單引號:var js_1=document.getElementById(‘div1’);
  2. 單引號:onclick=”set(‘width’,’400px’)”
  3. 雙引號 :一般我不在 js中用雙引號,除非特殊情況例
<input type="button" onclick="alert("1")">-------------------不正確
<input type="button" onclick="alert('1')">-------------------正確

即 程式碼內部有單引號時必須用雙引號,其他情況本人一般都用單引號

  • 加引號的是字串常量(例如 id ,class)
  • 不加引號的是變數(還有基本所有形參,和一些非實參)、、

資歷尚淺,或許有我不知道的,謝謝評價

送給 一段程式碼 ,上面有我說的情況,程式碼實現,不做解釋

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>無標題文件</title>
<style>
div {width:200px; height:200px; margin:20px; float:left; background:yellow; border:10px solid black; filter:alpha(opacity:30); opacity:0.3;}
</style>
<script>
window.onload=function ()
{
    var oDiv1=document.getElementById('div1');

    oDiv1.onmouseover=function ()
    {
        startMove(this, 'opacity', 100);
    };
    oDiv1.onmouseout=function ()
    {
        startMove(this, 'opacity', 30);
    };
};

function getStyle(obj, name)
{
    if(obj.currentStyle)
    {
        return obj.currentStyle[name];
    }
    else
    {
        return getComputedStyle(obj, false)[name];
    }
}

function startMove(obj, attr, iTarget)
{
    clearInterval(obj.timer);
    obj.timer=setInterval(function (){
        var cur=0;

        if(attr=='opacity')
        {
            cur=parseFloat(getStyle(obj, attr))*100;
        }
        else
        {
            cur=parseInt(getStyle(obj, attr));
        }

        var speed=(iTarget-cur)/6;
        speed=speed>0?Math.ceil(speed):Math.floor(speed);

        if(cur==iTarget)
        {
            clearInterval(obj.timer);
        }
        else
        {
            if(attr=='opacity')
            {
                obj.style.filter='alpha(opcity:'+(cur+speed)+')';
                obj.style.opacity=(cur+speed)/100;
            }
            else
            {
                obj.style[attr]=cur+speed+'px';
            }
        }
    }, 30);
}
</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>