如何使用javascript更改html中的属性 [英] how to change attribute in html using javascript

查看:103
本文介绍了如何使用javascript更改html中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,那么如何更改width属性?

This is my code, so how can i change the width attribute?

<html>
<head>
<script type="text/javascript">
 document.getElementById("cpul").src="hello.jpg";
</script>
</head>
<body>

<img src="hi.jpg" width="100" height="100" id="cpul">

</body>
</html>

上述情况失败,图片完全没有变化!!

The above is fail and the image no change at all!!

但是为什么当我使用这段代码(从其他网站复制)时,图片就会改变

But why when i use this code(copy from other site), the image is change

<html>
<head>
<title>JS DD Function</title>
<script type="text/javascript">
    function jsDropDown(imgid,folder,newimg)
 { 
 document.getElementById(imgid).src="http://www.cookwithbetty.com/" + folder + "/" + newimg + ".gif";
 }
</script>
</head>
<body>
<table>
  <tr>
    <td>
Foods: <select name="food" onChange="jsDropDown('cful','images',this.value)">
       <option value="steak_icon">Steak</option>
    <option value="salad_icon">Salad</option>
    <option value="bread_icon">Bread</option>
    </select><br />
     </td>
  <td>
         <img src="http://www.cookwithbetty.com/images/steak_icon.gif" id="cful">

</body>
</html>


推荐答案

您的代码无法正常工作的最可能原因是它是在元素存在于DOM之前执行的。您应该将代码设置为在窗口 load 事件上运行,或者将其放在文档的末尾,以确保在您尝试访问它之前该元素存在。

The most likely reason that your code is not working is that it is being executed before the element exists in the DOM. You should set your code up to run on the window load event or place it at the end of the document to ensure that the element exists before you try to access it.

<html>
<head>
   <title>Foo</title>
</head>
<body>

<img src="hi.jpg" width="100" height="100" id="cpul">
<script type="text/javascript">
   document.getElementById("cpul").src="hello.jpg";
</script>
</body>
</html>

这篇关于如何使用javascript更改html中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆