简体   繁体   中英

javascript - passing a string to innerHTML

This onmouseover 'lookdown' function works but the onmouseout 'lookup' function does not:

function lookdown(harvid) { harvid.innerHTML="See details below"; }
function lookup(harvid,crop) {harvid.innerHTML=crop;}

<td id="harv1244" onmouseover="lookdown(harv1244)"
onmouseout="lookup(harv1244,apples)">dummy</td>

This onmouseout function works (although, of course, it prints 'crop' and I want to pass in a string as I am trying to do above):

function lookup(harvid) {harvid.innerHTML="crop";}

<td id="harv1244" onmouseover="lookdown(harv1244)"
onmouseout="lookup(harv1244)">dummy</td>

There are several issues with your code:

  • You are passing undeclared variables into your functions. apples and harvid are variables, not strings, and therefore undefined. You need to put those values in quotes to make them strings

  • harvid needs to either be a string or a node element. But you are not passing in either. Assuming you want it to be a string, you then need to find the DOM element using getElementById .

Here is a working solution:

Javascript:

function lookdown(harvid) { 
    document.getElementById(harvid).innerHTML="See details below"; 
}

function lookup(harvid,crop) {
    document.getElementById(harvid).innerHTML=crop;
}

HTML:

<div id="harv1244" onmouseover="lookdown('harv1244')"
onmouseout="lookup('harv1244','apples')">
    dummy
</div>

And here the associated fiddle: http://jsfiddle.net/pQM37/

EDIT:

To make this code a little cleaner, you could pass the element itself into the function, instead of the id , like this:

Javascript:

function lookdown(ele) { 
    ele.innerHTML="See details below"; 
}

function lookup(ele,crop) {
    ele.innerHTML=crop;
}

HTML:

<div id="harv1244" onmouseover="lookdown(this)"
onmouseout="lookup(this,'apples')">
    dummy
</div>

Fiddle: http://jsfiddle.net/pQM37/1/

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