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

asp.net - How to put image in anchor tag dynamically using javascript - Stack Overflow

programmeradmin2浏览0评论

I have dynamically created image in javascript. I want img to be placed inside an anchor tag how can i do this?

        var element = document.createElement("img");
        element = cell.appendChild(element);
        element.setAttribute("src", "/Images/Delete.gif");

I have dynamically created image in javascript. I want img to be placed inside an anchor tag how can i do this?

        var element = document.createElement("img");
        element = cell.appendChild(element);
        element.setAttribute("src", "/Images/Delete.gif");
Share Improve this question asked May 9, 2011 at 10:11 Ulhas TuscanoUlhas Tuscano 5,62015 gold badges59 silver badges90 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9
var anchor=document.createElement('a');
anchor.href='#';
var element = document.createElement("img");
element.setAttribute("src", "/Images/Delete.gif");
anchor.appendChild(element);
cell.appendChild(anchor);

i did not test the code, i used my brain as interpreter, so there may be an error in it. but i think you should get the concept.

You'll need a reference to the anchor tag (node). Let's say that's a. Since A and IMG are very simple html elements, this will work just fine:

a.innerHTML += '<img src="/Images/Delete.gif">';

Or if you want to replace the content of the A tag (instead of add the img), just remove the +:

a.innerHTML = '<img src="/Images/Delete.gif">';

Can't fail. In any browser. jQuery is overkill for something this simple (and would do the exact same underneath).

edit
But it looks you're inserting the img into a cell and not an anchor tag... Or your anchor tag is called cell? In that case, just replace a. with cell. =)

element.setAttribute before you append it as you are redclaring element to what I presume to now be the cell... or don't assign element = cell.append..

var element = document.createElement("img");
element.setAttribute("src", "/Images/Delete.gif");
cell.appendChild(element);

What I suggest though would be:

function insertImage(anchorID, imagesrc){
  var img = "<img src='" + imagesrc + "' alt='image' />";
  $("#"+anchorID).html($("#"+anchorID).html() + img);
}

I am adding html within html in case there is any text in there you still want to keep.. otherwise negate that second statement of html

You need the jQuery javascript plugin for this to work.. http://docs.jquery./Downloading_jQuery

If you'd prefer not to include a plugin, then:

function insertImage(anchorID, imagesrc){
      var img = "<img src='" + imagesrc + "' alt='image' />";
      document.getElementById(anchorID).innerHtml = img;
    }
发布评论

评论列表(0)

  1. 暂无评论