简体   繁体   English

动态更改HTML <img> 使用Java脚本或JQuery的src属性

[英]Dynamically change the HTML <img> src attribute using Java Script or JQuery

I need to change the html img src value dynamically from the value from hidden text field using Jquery or Java script. 我需要使用Jquery或Java脚本从隐藏文本字段中的值动态更改html img src值。

<p><img id="yui_img" height="333" width="345"></p>

function onImgChange()
 {
document.getElementById('yui_img').src=document.getElementById('addProductLinksCreateForm:addProductLinkUrlValue').value;

 }

I got the value in the DOM but it is not getting reflected in it. 我在DOM中获得了价值,但并没有得到体现。 Old image is maintained. 保留旧图像。

This should work, but you need to ensure that these are the case: 这应该可以,但是您需要确保是这种情况:

  • Does the textbox tag look like <input type="text" id="addProductLinksCreateForm:addProductLinkUrlValue"> ? 文本框标签看起来像<input type="text" id="addProductLinksCreateForm:addProductLinkUrlValue">吗?

  • Are you calling onImgChange() at all? 您是否在调用onImgChange() You could try document.getElementById('addProductLinksCreateForm:addProductLinkUrlValue').onchange = onImgChange; 您可以尝试document.getElementById('addProductLinksCreateForm:addProductLinkUrlValue').onchange = onImgChange; to allow that to happen when the user switches to a different text box. 以便在用户切换到其他文本框时发生这种情况。

Using jQuery, it would look like: 使用jQuery,它看起来像:

function onImgChange() {
     $('#yui_img').attr('src', function(i, src) {
         return $('#addProductLinksCreateForm').attr('src');
     });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM