[英]why do some js parameters require quotation marks and others don't?
我的頁面上有這個功能:
function selected(elmnt, name, id2check) {
var x = document.getElementById(id2check).checked;
if(x == false) {
elmnt.style.backgroundColor = "#18436C";
name.style.color = "#f9FfFf";
document.getElementById(id2check).checked = true;
} else {
elmnt.style.backgroundColor = "transparent";
name.style.color = "#18436C";
document.getElementById(id2check).checked = false;
}
}
傳遞的第一個參數是不需要引號的“this”。 另外兩個分別是 div 和輸入(復選框)的 id 名稱。 該函數工作的唯一方式是第三個參數有引號但第二個參數沒有。 這是為什么?
<div id="abbsmalone_container" onclick="selected(this, abbsmalone_name, 'abbsmalone_select')">
<input type="checkbox" class="selections" name="abbsmalone_select" id="abbsmalone_select" value="yes" checked='checked' >
那是因為id2check
是 String 類型。 在將值分配給String
類型的變量時,所有 String 類型都必須與""
或''
符號一起使用,要么必須使用 "" 或 '' 要么應該是String
類型。 還有一件事,你不需要使用這個, if(x == false)
這里 x 是一個布爾值所以條件應該是if(!x)
因此你的代碼看起來像,
function selected(elmnt, name, id2check) {
var x = document.getElementById(id2check).checked;
if(!x) {
elmnt.style.backgroundColor = "#18436C";
name.style.color = "#f9FfFf";
document.getElementById(id2check).checked = true;
} else {
elmnt.style.backgroundColor = "transparent";
name.style.color = "#18436C";
document.getElementById(id2check).checked = false;
}
}
在這里, elmnt
是一種object
類型,因此您不需要使用""
或''
,因此您可以使用this
。 您可以將""
或''
用於String
類型的事物。
還有一件事,你正在使用name.style.color
,它說即使name
不是String
類型,它是一個對象。 您將一個String
傳遞給document.getElementById()
,即您傳遞一個id
,一個 html 元素 id,它是String
類型,因此這里elmnt
是Object
類型, name
是Object
類型, id2check
是String
類型。 因此,對id2check
使用""
或''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.