最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Changing The Image Source Using Javascript - Stack Overflow

programmeradmin2浏览0评论

I have a snippet that is like this:

<div id="image_input">
    <img src="missing-image.png" name="image_p" />
    <input type="text" name="image_url" size="37" />
</div>

I want that when someone unfocus image_url or even do a onChange event, a Javascript function called changeImage() be raised(this I already know how to do, now es what I don't) and change the image_p changes to the URL that is written in image_url. How to do this?

I have a snippet that is like this:

<div id="image_input">
    <img src="missing-image.png" name="image_p" />
    <input type="text" name="image_url" size="37" />
</div>

I want that when someone unfocus image_url or even do a onChange event, a Javascript function called changeImage() be raised(this I already know how to do, now es what I don't) and change the image_p changes to the URL that is written in image_url. How to do this?

Share Improve this question asked Jan 11, 2011 at 3:25 Nathan CamposNathan Campos 29.5k62 gold badges200 silver badges307 bronze badges 2
  • maybe document.getElementByName('image_p').src = document.getElementByName('image_url').value; – Zhasulan Berdibekov Commented Jan 11, 2011 at 3:31
  • 2 getElementByName is not a function, only getElementsByName. This is because the name does not need to be unique like id. getElementsByName returns an array of objects with the specified name. – Mark Baijens Commented Jan 11, 2011 at 3:34
Add a ment  | 

3 Answers 3

Reset to default 4
document.getElementsByName("image_p")[0].src = document.getElementsByName("image_url")[0].src;

if you have more elements with the same name you can loop trough them or use id's if you want to be sure it you do this for only 1 element.

<div id="image_input">
    <img src="missing-image.png" name="image_p" id="image_p" />
    <input type="text" name="image_url" size="37" id="image_url" />
</div>

You can define ids for both the elements and have this in your onChange function:

document.getElementById('image_p').src = document.getElementById('image_url').value;
<div id="image_input">
    <img src="missing-image.png" id="image_p" />
    <input type="text" name="image_url" id="image_url" size="37" />
</div>

<script type="text/javascript">
    jQuery('#image_url').bind('change blur', function () {
        jQuery('#image_p').attr('src', this.value);
    });
</script>
发布评论

评论列表(0)

  1. 暂无评论