问题描述:

I m new in javascript developpement

i m trying to make e function which hide or show some text in a span after a specific mouse event and i want to pass the id of this span in my function

this is my script which work with only a specific id which is "sp1" in this case but i want to pass the id in my function parametres

<script>function myOverFunction() {

document.getElementById("sp1").style.visibility = 'visible';}

function myOutFunction() {

document.getElementById("sp1").style.visibility = 'hidden';}

and this a part of my html code

<div id="lg1"onmouseover="myOverFunction()" onmouseout="myOutFunction()"></div>

<center>

<div>

<span id="sp1" style="visibility: hidden;" >Current Value :70 <br>Target :80 <br>

<div class="label label-blue">In progress 90%</div>

</span>

</div>

</center>

网友答案:

Passing a parameter to a function like that can be achieved by using either single or double quotes depending on what you've used to enclose the code in your html.

<div id="mydiv" onclick="myFunction('mydiv');"></div>

Doing this is not really the best way to do it though.

When "myFunction" is fired by the onclick event, by default an e (event) parameter is passed. This contains lots of information about the event that happened, including a reference to the object that fired it. So you can find the id of your element using it.

function myFunction(e) {
    e = e || window.event;
    alert(e.target.getAttribute("id"));
}

And your HTML would be...

<div id="myDiv" onclick="myFunction()"></div>

Edit:

Looking at your question a little further, you can combine this, and your two functions into one toggling function

function toggleVisibility(e) {
    e = e || window.event;
    if (e.target.style.visibility == "visible") {
        e.target.style.visibility = "hidden";
    } else {
        e.target.style.visibility = "visible";
    }
}

You can call the same function for onmouseover and onmouseout on any element providing the visibility property is not null (i think it defaults to visible? bit of a guess thouugh)

相关阅读:
Top