2013-10-13 105 views
-1

我這裏有一個問題,或者更像是困惑。所以我知道通過javascript改變HTML屬性的基礎知識。例如:更改屬性Javascript方式的值

<iframe id="iframe" src="http://www.stackoverflow.com/" width="610px"> 

因此,爲了與ID「的iframe」改變寬度的屬性的元素是:

document.getElementById("iframe").setAttribute("width", "700px"); 

但我怎麼能更改通過JavaScript的屬性,當談到這樣的方式? (注意寬度的屬性之間的差異)

<iframe id="iframe" src="http://www.stackoverflow.com/" width=610> 

回答

2

But how can I change attribute via javascript when it comes like this way?

如出一轍:

.setAttribute("width", "700px"); 

.setAttribute("width", "700"); 

.setAttribute("width", 700); 

請注意,所有屬性值都被認爲是字符串。 HTML語法只允許您在某些情況下省略引號,但不會更改數據類型。從HTML specification

By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39).

[...]

In certain cases, authors may specify the value of an attribute without any quotation marks. The attribute value may only contain letters (a-z and A-Z), digits (0-9), hyphens (ASCII decimal 45), periods (ASCII decimal 46), underscores (ASCII decimal 95), and colons (ASCII decimal 58). We recommend using quotation marks even when it is possible to eliminate them.

如果你看一下DOM API specification,你可以看到setAttribute被定義爲接受DOMString作爲參數。 JavaScript實現將相應地將您傳遞的任何值轉換爲此方法。

+0

謝謝你的解釋:) – Natsume

+0

+1不用說「只是使用jQuery的'.attr()'方法。:) – Scottie

1

完全相同的方式。雖然在第二個例子中,您沒有正確設置id

<iframe id="iframe" src="http://www.stackoverflow.com/" width=610> 
<--  ^added equal sign here        --> 

與該改變你的代碼工作正常:http://jsfiddle.net/FECq3/

+0

哦等號是錯字錯誤,沒有注意到它xD。 Ooops – Natsume

+0

@Natsume你應該在你的javascript控制檯看到這個錯誤:'未捕獲的TypeError:不能調用'null'的方法'setAttribute',它告訴你你沒有找到你想要的元素。閱讀你的錯誤! –

+0

很抱歉,我在這些示例中的記事本中輸入了它們。我完全忘了int和String,直到使者提到他們xD – Natsume