用法

2013-10-31 45 views
0

代碼:用法

activeCell.onclick = function() 
{ 
    console.log(element); 
    element.value = this.value; 
    console.log(element.value); 
    console.log(element); 
}; 

比方說activeCell值= 「678」元件跨度只是一個簡單的輸入標籤()

<input id="calendar" value="123" /> 

輸出:

<input id="calendar" value="123"> 
678 
<input id="calendar" value="123"> 

字符串被替換爲,但輸入標籤值保持不變。然而,當的方法SetAttribute使用輸出值被改變:

element.setAttribute("value", this.value); 

我用的是element.value = XXX自從前,它的工作...有什麼區別?

+0

Span元素是否具有名爲「Value」的屬性? – AmGates

+0

當屬性爲標準並且語法可用時使用'element.propertyName'。 –

+0

@AmGates只是一個例子。這不是正確的風格,但它是可能的。在桌子上使用它。 – sitilge

回答

0

根據您的示例,「value」屬性是元素類型「input」的預定義屬性,但不是元素類型「span」的預定義屬性。因此,根據您的功能

<input id="calendar" value="123"> 
    <span id="activeCell">678</span> 

document.getElementById('activeCell').onclick = function(){ 
    element = document.getElementById('calendar'); 
    console.log(element); 
    element.value = this.value; // Here this object doesn't have the property value hence it will be assigned with value as undefined; 
    console.log(element.value); 
    console.log(element); 
}; 

"this" object referring to the Span element does not have the property `"value"` by default hence it returns undefined. It is not the case with the setAttribute method. 

在setAttribute方法,您可以分配任何屬性的任何值。基本的功能是它檢查該對象的屬性堆棧,如果它找到你提到的屬性,那麼它爲它分配值。如果在屬性堆棧中找不到該屬性,那麼它將爲您指定的名稱創建該對象的新屬性,併爲其分配值。

so document.getElementById('activeCell')。setAttribute('value',「102」);它分配的屬性值爲102.

希望這可以幫助你理解