2017-06-18 47 views
0

重点在于通过更改元素的背景颜色来关注鼠标移动时网页的特定元素。如何将运行时参数从html代码传递给javascript函数

的HTML如下:

<html> 
<head> 
<base src="..... /> 
<script>....</script> 
<link..../> 
<title></title> 
</head> 
<body> 
<p style="font-size:20px;font-weight:bold"> Enter values or choose options 
in the form below .</p> 
<div id="d1"> 

<form id="f1" action="" method="post"> 
<fieldset> 
    <legend><a name="pdet"></a>Personal Details</legend> 
    <table id="t1" width="400" height="auto" rows="4" cols="2"> 
     <tr id="tr1" onMouseMove ="focus(tr1)" onMouseOut ="original(tr1)"> 
      <td><label for="fname">First Name :<label></td> 
      <td><input type="text" id="fname" col="30"></input></td> 
     </tr> 
     <tr id="tr2" onMouseMove ="focus(tr2)" onMouseOut ="original(tr2)"> 
      <td><label for="lname">Last Name : </label></td> 
      <td><input type="text" id="lname" col="30"></input></td>     
     </tr> 
    </table> 
</fieldset> 
</form> 
</div> 
<br/> 
</body> 
</html> 

中的JavaScript功能如下

function focus(e_id){ 
var element = document.getElementById("e_id").style.backgroundColor ="blue"; 
} 

function original(e_id){ 
var element = document.getElementById("e_id").style.backgroundColor="green"; 
} 

阅读,其中有人建议用“焦点这么做同一主题上一答( this)'或'focus(this.id)'作为参数来分别传递元素本身或者元素的id。试过了,但没有奏效。

任何人都可以帮我解决这个问题吗?

+2

“e_id”是一个字符串,不是对变量的引用 – epascarello

回答

0

这只是不正确使用引号的问题。

function elfocus(e_id){ 
 
// do not use quotes around e_id in order to use the function argument 
 
var element = document.getElementById(e_id).style.backgroundColor ="blue"; 
 
} 
 

 
function original(e_id){ 
 
var element = document.getElementById(e_id).style.backgroundColor="green"; 
 
}
<p style="font-size:20px;font-weight:bold"> Enter values or choose options 
 
in the form below .</p> 
 
<div id="d1"> 
 

 
<form id="f1" action="" method="post"> 
 
<fieldset> 
 
    <legend><a name="pdet"></a>Personal Details</legend> 
 
    <table id="t1" width="400" height="auto" rows="4" cols="2"> 
 
     <tr id="tr1" onMouseMove ="elfocus('tr1')" onMouseOut ="original('tr1')"> 
 
     <!-- put single quotes arount tr1 so that it is passed as a string --> 
 
      <td><label for="fname">First Name :<label></td> 
 
      <td><input type="text" id="fname" col="30"></input></td> 
 
     </tr> 
 
     <tr id="tr2" onMouseMove ="elfocus('tr2')" onMouseOut ="original('tr2')"> 
 
      <td><label for="lname">Last Name : </label></td> 
 
      <td><input type="text" id="lname" col="30"></input></td>     
 
     </tr> 
 
    </table> 
 
</fieldset> 
 
</form> 
 
</div> 
 
<br/>

我也改名为对焦功能,因为window.focus是现有的功能已经让事件侦听器可能不使用您的实现。

1

我认为你的主要问题可能是你使用的是"e_id"(一个字符串)而不是e_id(一个变量标识符)。

相关问题