跳转到内容

JavaScript/Changing elements

维基教科书,自由的教学读本

在 JavaScript 中,您可以使用以下语法更改元素:

element.attribute="new value" 

在这里,图像的src 属性发生了变化,因此当调用脚本时,它将图片从 myPicture.jpg 更改为 otherPicture.jpg:

//The HTML <img id="example" src="myPicture.jpg"> //The JavaScript document.getElementById("example").src="otherPicture.jpg"; 

为了改变一个元素,你可以使用它的参数名作为你想要改变的值。 例如,假设我们有一个按钮,我们希望更改它的值。

<input type="button" id="myButton" value="I'm a button!"> 

稍后在页面中,使用 JavaScript,我们可以执行以下操作来更改该按钮的值:

myButton = document.getElementById("myButton"); //searches for and detects the input element from the 'myButton' id myButton.value = "I'm a changed button"; //changes the value 

要更改输入的类型(例如,将按钮更改为文本),请使用:

myButton.type = "text"; //changes the input type from 'button' to 'text'. 

另一种更改或创建属性的方法是使用 element.setAttribute("attribute", "value")element.createAttribute("attribute", "value")。 使用 setAttribute 更改之前已定义的属性。

//The HTML <div id="div2"></div> //Make a div with an id of div2 (we also could have made it with JavaScript) //The Javascript var e = document.getElementById("div2"); //Get the element e.setAttribute("id", "div3"); //Change id to div3 

但是,如果您想设置一个以前没有定义过的值,请使用 createAttribute()

var e = document.createElement('div'); //Make a div element (we also could have made it with HTML) e.createAttribute("id", "myDiv"); //Set the id to "myDiv"