2013-10-13 48 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