简体   繁体   English

javascript-将字符串传递给innerHTML

[英]javascript - passing a string to innerHTML

This onmouseover 'lookdown' function works but the onmouseout 'lookup' function does not: 此onmouseover“查找”功能有效,但onmouseout“查找”功能无效:

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): 这个onmouseout函数可以正常工作(尽管当然,它会打印“ crop”,并且我想在上面尝试传递一个字符串):

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. applesharvid是变量,而不是字符串,因此未定义。 You need to put those values in quotes to make them strings 您需要将这些值放在引号中以使其成为字符串

  • harvid needs to either be a string or a node element. harvid必须是字符串或节点元素。 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 . 假设您希望它是一个字符串,则需要使用getElementById查找DOM元素。

Here is a working solution: 这是一个可行的解决方案:

Javascript: 使用Javascript:

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

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

HTML: HTML:

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

And here the associated fiddle: http://jsfiddle.net/pQM37/ 这里是相关的小提琴: 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: 为了使这段代码更简洁,您可以将元素本身而不是id传递给函数,如下所示:

Javascript: 使用Javascript:

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

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

HTML: HTML:

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

Fiddle: http://jsfiddle.net/pQM37/1/ 小提琴: http : //jsfiddle.net/pQM37/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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