【问题标题】:Adding image src in the inline html under javascriptjavascript下内联html中添加图片src
【发布时间】:2013-11-25 20:58:51
【问题描述】:

嗨,我在谷歌地图上点击标记时显示一个 infoWindow,infoWindow 的内容是一个内联 html 以及 img 标记,每个标记的图像的 src 都会发生变化,我想动态获取 img src代码 iv 所做的是

var contentString = '<div id="content">'+
  '<div id="siteNotice">'+
  '<img id="image" alt="No Photograph to Display" src="" width="400px" height="250px" />'+

  '</div>'+
  '<h1 id="firstHeading" class="firstHeading">'+title+'</h1>'+
  '<div id="bodyContent">'+
  '<p>'+probdesc+'</p><br>'+
  '<p><b>Open Date:</b>'+opendate+'</p><br>'+
   '<p><b>Status:</b>'+status+'</p><br>'+
  '</div>'+
  '</div>';

图片标签必须获取src值必须替换为包含图片动态路径的url值

var url = '<%=imageURL %>'+ "&<portlet:namespace/>imagepath=" + imagepath;

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    在页面上打印 HTML 代码后,您可以使用 jQuery:

    $("#image").attr("src", url); //"url" is your var.
    

    只有 Javascript:

    document.getElementById("image").setAttribute("src", url);
    document.getElementById("image").src = url; //it works too - http://www.w3schools.com/js/js_htmldom_html.asp
    

    在 Paul S 发表评论后,只是为了简单起见。如果您不在页面上打印 HTML,“attr”代码将不起作用。要在您的页面上打印 HTML 代码,您可以使用:

    $("#anchor_element").html(contentString);
    // and then
    $("#image") .....
    

    使用纯 Javascript:

    document.getElementById("anchor").innerHTML = contentString;
    // and then
    document.getElementById("image")......
    

    【讨论】:

    • 只是指出 #image 必须以 Node 的形式存在,然后才能使用。
    • 好点,Paul S。我说的是“在您的页面上打印 HTML 代码之后”,我记得 HTML 代码正在某个地方打印。编辑答案。
    猜你喜欢
    • 1970-01-01
    • 2013-07-30
    • 2023-04-02
    • 2013-11-30
    • 2013-03-21
    • 1970-01-01
    • 2013-11-17
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多