簡體   English   中英

Javascript不適用於Chrome和Firefox,但適用於IE

[英]Javascript doesn't work on Chrome and Firefox, but works on IE

我有這行代碼可在IE上使用

Javascript:

function getInfo() {
    var date = new Date(date);
    var month = date.getMonth();
    var test = "print";
    document.getElementById('lol').value = month;
}

身體:

<input type=text name=lol>
<input type=button onClick=getInfo() value=lol>

它適用於IE,但不適用於Chrome和Firefox。 Chrome和Firefox是否具有不同的Javascript?

getElementById用於通過id查找元素。 您的輸入沒有id ,只有一個name 您的代碼可在IE上使用,因為IE(某些版本) 感到困惑,並從getElementById返回具有name屬性的元素。 這是IE中的錯誤。

要解決此問題,請在您的輸入中添加id="lol"

<input type=text name=lol id=lol>
<input type=button onClick=getInfo() value=lol>

...或使用querySelector("[name=lol]")

document.querySelector('[name=lol]').value = month;

querySelector返回它可以找到的與給定CSS選擇器匹配的第一個元素。 它在所有現代瀏覽器和IE8上都可用。

分別:您的代碼undefined傳遞給Date構造函數,這里:

var date = new Date(date);

...因為該代碼實際上是:

var date;
date = new Date(date);

...並且變量從值undefined

在使用符合標准的JavaScript引擎的瀏覽器上,您將得到一個無效的日期,因為規范要求引擎將參數轉換為數字,然后將其用作底線“時間值”(毫秒-自從-時代)。 undefined轉換為數字會產生NaN (“非數字”); 使用NaN作為其“時間值”的日期稱為無效日期。 在它們上使用getMonth和類似的返回NaN

如果要使用當前日期,則根本不用參數:

var date = new Date();

這是使用id且未將undefined傳遞給Date代碼的有效版本(經過最少的修改):

 function getInfo() { var date = new Date(); var month = date.getMonth(); var test = "print"; document.getElementById('lol').value = month; } 
 <input type=text name=lol id=lol> <input type=button onClick=getInfo() value=lol> 

這是一個使用querySelectorname

 function getInfo() { var date = new Date(); var month = date.getMonth(); var test = "print"; document.querySelector('[name=lol]').value = month; } 
 <input type=text name=lol> <input type=button onClick=getInfo() value=lol> 


旁注:我真的會將onClick屬性的內容括在引號中,因為它包含非字母數字字符。 根據規范 ,您的標記應該可以正常運行,並且可以在Chrome上運行(無引號的語法允許使用空格, "'<>` ),但是...

我建議使用Jquery

<input type=text id="somethingElse">
<input type=button id="something">


$( "#something" ).click(function() {
    var currentMonth = (new Date).getMonth() + 1;
    $( "#somethingElse" ).val(currentMonth);
});

您缺少引號和id

<input type="text" id="lol" name="lol">
<input type="button" onClick="getInfo();" value="lol">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM