简体   繁体   English

更改属性Javascript方式的值

[英]Change value of attribute Javascript way

I have a problem here, or more like confused. 我在这里遇到问题,或更困惑。 So I know the basics of changing attribute in html via javascript. 所以我知道通过javascript更改html属性的基础。 For example: 例如:

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

So to change the attribute of width for element with id "iframe" would be: 因此,更改ID为“ iframe”的元素的width属性将是:

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

But how can I change attribute via javascript when it comes like this way? 但是,当这种方式出现时,如何通过javascript更改属性? (notice the difference between width's attribute) (注意width属性之间的差异)

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

But how can I change attribute via javascript when it comes like this way? 但是,当这种方式出现时,如何通过javascript更改属性?

Exactly the same: 一模一样:

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

or 要么

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

or 要么

.setAttribute("width", 700);

Note that all attribute values are considered to be strings anyways. 请注意,无论如何,所有属性值都被视为字符串。 The HTML syntax just allows you to omit quotation marks in certain circumstances, but that doesn't change the datatype. HTML语法仅允许您在某些情况下省略引号,但这不会更改数据类型。 From the HTML specification : 根据HTML规范

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). 默认情况下,SGML要求使用双引号(ASCII十进制34)或单引号(ASCII十进制39)来分隔所有属性值。

[...] [...]

In certain cases, authors may specify the value of an attribute without any quotation marks. 在某些情况下,作者可以指定属性的值而无需任何引号。 The attribute value may only contain letters (az and AZ), digits (0-9), hyphens (ASCII decimal 45), periods (ASCII decimal 46), underscores (ASCII decimal 95), and colons (ASCII decimal 58). 该属性值只能包含字母(az和AZ),数字(0-9),连字符(ASCII十进制45),句点(ASCII十进制46),下划线(ASCII十进制95)和冒号(ASCII十进制58)。 We recommend using quotation marks even when it is possible to eliminate them. 我们建议即使在可能的情况下也使用引号。

If you look at the DOM API specification , you can see that setAttribute is defined to accept a DOMString as argument. 如果查看DOM API规范 ,则可以看到setAttribute已定义为接受DOMString作为参数。 The JavaScript implementation will convert any value you pass to this method accordingly. JavaScript实现将相应地将传递给此方法的任何值转换为该方法。

Exactly the same way. 完全一样。 Although, in your second example, you didn't set the the id properly. 尽管在第二个示例中,您没有正确设置id

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

With that change your code works fine: http://jsfiddle.net/FECq3/ 进行此更改后,您的代码可以正常运行: http : //jsfiddle.net/FECq3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM