javascript设置src属性的方法:首先使用“document.getElementById("id值")”语句获取元素对象;然后使用“元素对象.setAttribute("src","URL地址")”语句来添加或修改元素属性。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
javascript设置src属性
在javascript中,可以使用setAttribute()方法来设置元素src属性,代码示例如下:
@@##@@ <p id="demo">点击按钮来设置img图片的 src属性。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { document.getElementById("img").setAttribute("src", "img/3.jpg"); } </script>
效果图:
立即学习“Java免费学习笔记(深入)”;
说明:setAttribute()方法
setAttribute() 方法添加指定的属性,并为其赋指定的值。如果这个指定的属性已存在,则仅设置/更改值。
语法
element.setAttribute(attributename,attributevalue)
参数 | 类型 | 描述 |
---|---|---|
attributename | String | 必需。您希望添加的属性的名称。 |
attributevalue | String | 必需。您希望添加的属性值。 |
【推荐学习:javascript高级教程】
以上就是javascript怎么设置src属性的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号