简体   繁体   中英

Changing text by clicking an image

I am a javascript noob.

I want clicking on the images to change the text in a span

What I have so far:

Image:

    <img src="image.png" onclick="document.span[0].elements['videoTitle'].value = 'My Text'" />

Span:

    <span name="videoTitle"><strong>My Initial Text</strong></span>

I dont know what should follow "document." and I assume i need javascript in the header or something?

I was referencing this post: click on image and change a text

I have no idea what I'm doing here. I don't understand js, I'm a designer!

Span's do not have value properties. You need to use innerHTML in this case, like so:

<img src="image.png" onclick="document.getElementsByName('videoTitle')[0].getElementsByTagName('strong')[0].innerHTML = 'My Text'" />

This will change the text of the first element with name videoTitle on your page.

Fiddle: http://jsfiddle.net/duffmaster33/7j59H/

I think you are looking for this:-

 document.getElementsByName('videoTitle')[0] // assuming this is the first element with  
                                             //the name `videoTitle`
.getElementsByTagName('strong')[0]
 .innerHTML = 'My Text'

SO it will be

<span name="videoTitle"><strong>My Initial Text</strong></span>
<img src="image.png" onclick="document.getElementsByName('videoTitle')[0].getElementsByTagName('strong')[0].innerHTML = 'My Text'" />
This is native old way and is supported in all browsers.

Demo

I recommend do something like this:

<img src="image.png" onclick="document.getElementsByName('videoTitle')[0].getElementsByTagName('strong')[0].innerHtml= 'My Text'" />

or

<img src="image.png" onclick="myFunc()" />
<script>
function myFunc(){
document.getElementsByName('videoTitle')[0].getElementsByTagName('strong')[0].innerHtml="my text";
}
</script>

I also advice to give the span an id and select it by ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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