[英]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: 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(this)之外的函数。 functionname(textmessage); functionname(textmessage);
what other ways can i pass information like elements into a function? 我还可以通过哪些其他方式将元素等信息传递给函数?
In your buttons callback, you are calling highlight(p)
. 在按钮回调中,您正在调用highlight(p)
。 In this context p
is an undefined variable, thus nothing gets highlighted. 在这种情况下, p
是未定义的变量,因此不会突出显示任何内容。 I suggest you give your <p>
element an ID and modify the callback to retrieve the <p>
element by its ID: 我建议您给<p>
元素提供一个ID,并修改回调以通过其ID检索<p>
元素:
<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: 当然,最好将所有回调代码移至其自身的函数中,并将其注册为按钮的click事件的回调,这将更好:
/* 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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.