![](/img/trans.png)
[英]how i can use toggle and function that remove the class from the previous element together only using JavaScript i have tried to Different ways?
[英]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";
}
HTML:
<p>Whatever</p>
<button onclick="hide(this,true); debug('hide button 1'); highlight(p);">hide button</button>
在上面的示例中,我在獲取高亮功能以突出顯示段落元素時遇到了麻煩。 有人可以告訴我我在做什么錯嗎?
我也想知道我如何使用除functionname(this)之外的函數。 functionname(textmessage);
我還可以通過哪些其他方式將元素等信息傳遞給函數?
在按鈕回調中,您正在調用highlight(p)
。 在這種情況下, p
是未定義的變量,因此不會突出顯示任何內容。 我建議您給<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>
當然,最好將所有回調代碼移至其自身的函數中,並將其注冊為按鈕的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.