Вопрос

So I JUST asked a question and I've already hit another roadblock. Thanks so much to the stackoverflow community for helping me out so much recently :)

Every time I see people changing the innerHTML of some tag, they use document.getElementByID(id).innerHTML. My images do NOT have ids, nor do I want to give each and every one of them an id.

Here is my code:

function clickImages()
{
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++)
{
     var delegate = function() { hover(this); };

  images[i].onmouseover = delegate;
}
}

function hover(img)
{
img.innerHTML = "Text!";
}

The innerHTML doesn't seem like it's working; when I mouse over the image nothing changes.

Thanks in advance! Let me know if I can clarify!

Это было полезно?

Решение

An image is itself a replaced element, so there is no innerHTML to replace.

Based on your comment, if you want to add HTML adjacent to the image, you could do this:

img.insertAdjacentHTML('afterend', 'HTML code');

You could also change 'afterend' to 'beforebegin' if you wanted to add the HTML before the image.

Writing on the image itself would be much more complicated and would require positioning another element above it with a transparent background, or using the image itself as the background of another element, or a variety of other similar techniques.

Другие советы

Element.innerHTML

innerHTML sets or gets the HTML syntax describing the element's descendants

innerHTML means the HTML that comes between the start and end HTML tags. Images don't have innerHTML

I am not sure what you want to achieve.

If you want to have a text displayed onmouseover, you can use the title attribute to do that.. for example:

<img src="smiley.gif" alt="Smiley face" title="Hello" />

If you are trying to replace the image with text on onmouseover ... then as an example (only to show the possibilities), the following code will hide the image & display a text onmouseover and make the image visible & remove the text onmouseout (although not very satisfactorily IMHO, more work has to be done on the code to improve it)

Please note: There shouldn't be any gap between the image tag and the span for this particular code to work. Also, a negative margin-left added to the span element can make it appear over the location of the image.

<img onmouseover="toText(this)" onmouseout="toImage(this)" src="smiley.gif" alt="Smiley" /><span style="visibility: hidden; margin-left: -30px;">Show Text</span>

function toText(img) {

 img.style.visibility = 'hidden';
 img.nextSibling.style.visibility = 'visible';
}

function toImage(img) {

  img.style.visibility = 'visible';
  img.nextSibling.style.visibility = 'hidden';
}

Good luck :)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top