简体   繁体   English

隐藏的div不会在点击时显示-Javascript,没有Jquery

[英]Hidden div will not show on click - Javascript, no Jquery

Just like my description says. 就像我的描述说的那样。

Fiddle 小提琴

<div id="step2" class="question">
    <p>Step two:</p>
    <div id="resultOne" class="script">
        <p>"Test Yes!</p>
    </div>
    <div id="resultTwo" class="script">
        <p>"Test No"</p>
    </div>
</div>

The above div isn't responding to button clicks. 上面的div对按钮点击没有响应。 It seems like the corresponding JS function isn't even being called. 似乎甚至没有调用相应的JS函数。

I know it's probably a minor syntax error, but I can't find it for the life of me. 我知道这可能是一个较小的语法错误,但是我一生都找不到。

Thank you for the help. 感谢您的帮助。

I could not get it to work in the fiddle, it said that the nextStep function was not available. 我无法使它在小提琴中工作,它说nextStep函数不可用。 But this definition of nextStep should work: 但是nextStep的定义应该起作用:

function nextStep(divShow, divHide, divReveal) {
    var show = document.getElementById(divShow);
    var hide = document.getElementById(divHide);
    var reveal = document.getElementById(divReveal);
    show.style.display = "inline-block";
    hide.style.display = "none";
    if (reveal.style.display == "none") 
        reveal.style.display = "block";
}

And change your buttons to this: 并将您的按钮更改为此:

<button type="button" onclick="javascript:nextStep('resultOne', 'resultTwo', 'step2')">Yes</button>
<button type="button" onclick="javascript:nextStep('resultTwo', 'resultOne', 'step2')">No</button>

Notice that the " are gone around the parameters in the getElementById call? What you were trying to get was the element named divShow, not the one referenced to by the content of the variable. 注意,“”遍历了getElementById调用中的参数吗?您试图获取的是名为divShow的元素,而不是变量内容所引用的元素。

It appears the function isn't called because jsfiddle wraps your javascript in an anonymous function that executes on window load. 似乎未调用该函数,因为jsfiddle将您的JavaScript封装在一个匿名函数中,该函数在窗口加载时执行。 That means the scope of the function you declared is only within that function. 这意味着您声明的函数的范围仅在该函数之内。

Instead, try attaching it as a global function 而是尝试将其附加为全局函数

window.nextStep = function (divShow, divHide, divReveal) {
    var show = document.getElementById(divShow);
    var hide = document.getElementById(divHide);
    var reveal = document.getElementById(divReveal);
    show.style.display = "inline-block";
    hide.style.display = "none";
    if (reveal.style.display == "none") 
        reveal.style.display = "block";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM