简体   繁体   中英

What are different ways i can use function arguments in javascript

function hide (x, reflow2) {
  if (reflow2) { 
    x.style.display = "none";
  } 
  else {
    x.style.visibility = "hidden";
  }
}

function debug(msg) {
  //find the debugging section of the document, looking at html id attributes
  var log = document.getElementById("debuglog");

  //if no element with the id "debuglog" exists, create one.

  if (!log) {
    log = document.createElement("div");
    log.id = "debuglog"; 
    log.innerHTML = "<h1> Debug log </h1>";
    document.body.appendChild(log);
  }

  //now wrap the message in its own <pre> and append it to the log

  var pre = document.createElement('pre');
  var text = document.createTextNode(msg);
  pre.appendChild(text);
  log.appendChild(pre);
}

function highlight(e) { 
  var divi = document.getElementByTagName('p');

  if (!e.className)
    e.className="hilite";
 }
 else {
   e.className += "hilite";
  }

the html:

<p>Whatever</p>
<button onclick="hide(this,true); debug('hide button 1'); highlight(p);">hide    button</button>

In the example above, i'm having trouble getting the highlight function to highlight the paragraph element. can someone please show me what i'm doing wrong?

I would also like to know how i can use functions other than functionname(this); functionname(textmessage);

what other ways can i pass information like elements into a function?

In your buttons callback, you are calling highlight(p) . In this context p is an undefined variable, thus nothing gets highlighted. I suggest you give your <p> element an ID and modify the callback to retrieve the <p> element by its ID:

<p id="myP">Whatever</p>

<button onclick="hide(this, true);
                 debug('hide button 1');
                 highlight(document.getElementById('myP'));">Hide button</button>

Of course, it would be even better to move all that callback code in a function of its own and register it as a callback for the button's click event:

/* In HTML: */
<p id="myP">Whatever</p>
<button id="hideBtn">Hide button</button>

/*  In JS */
window addEventListener("DOMContentLoaded", function() {
    var myP = document.getElementById("myP");
    var btn = document.getElementById("hideBtn");
    btn.addEventListener("click", function() {
        hide(btn, true);
        debug('hide button 1');
        highlight(myP);
    });
});

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