js 改变change方法_JS获取和设置元素的属性以及属性值
时间: 2024-03-27 20:35:18 浏览: 35
获取元素属性值可以使用element.getAttribute(attributeName)方法,其中attributeName为属性名。例如,获取id属性值可以使用以下代码:
```
var element = document.getElementById("myDiv");
var idValue = element.getAttribute("id");
console.log(idValue); // 输出myDiv
```
设置元素属性值可以使用element.setAttribute(attributeName, attributeValue)方法,其中attributeName为属性名,attributeValue为属性值。例如,设置id属性值可以使用以下代码:
```
var element = document.getElementById("myDiv");
element.setAttribute("id", "newDiv");
console.log(element.id); // 输出newDiv
```
对于表单元素,可以通过监听change事件来获取用户修改后的值。例如,监听一个input元素的value值变化可以使用以下代码:
```
var inputElement = document.getElementById("myInput");
inputElement.addEventListener("change", function() {
console.log(inputElement.value);
});
```
当用户修改input元素的value值时,change事件会被触发,这时候我们就可以通过inputElement.value获取到用户修改后的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)