javascript 单击按钮时,如何将 style.display 从无更改为内联?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8184440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:34:43  来源:igfitidea点击:

How do I change style.display from none to inline when button is clicked?

javascript

提问by Zeynel

I want to display id="text"when the button is clicked. So I tried this:

我想在id="text"单击按钮时显示。所以我试过这个:

    <form name="i_choose_form" action="" method="post">
      <input type="submit" class="button" value="I am not sure, show me other choices..." onclick = "showText()"></br>
    </form>

    <span id ="text" style="display:none">First make your choice then you can see all other choices</span>

    <script type = "text/javascript">

function showText() { document.getElementById("text").style.display="inline"; }

</script>

But this does not work as expected and text is not displayed. What am I doing wrong? http://jsfiddle.net/dPhUQ/

但这不会按预期工作,并且不会显示文本。我究竟做错了什么?http://jsfiddle.net/dPhUQ/

采纳答案by Authman Apatira

It is shown, but you are submitting the page. Change your input to type='button' instead of 'submit'

它已显示,但您正在提交页面。将您的输入更改为 type='button' 而不是 'submit'

<input type="button" class="button" value="I am not sure, show me other choices..." onclick = "showText()"></br>

回答by epascarello

You are not cancelling the click event for the submit button so the page will submit the form.

您不会取消提交按钮的点击事件,因此页面将提交表单。

onclick = "showText(); return false;"

You should really look at adding the events unobtrusively.

您真的应该考虑不引人注意地添加事件。

<input type="submit" id="showMore" class="button" value="I am not sure, show me other choices..." onclick = "showText()">
<script type="text/javascript">
    function showText() { 
        document.getElementById("text").style.display="inline";
    }
    document.getElementById("showMore").click = showText;
</script>

回答by Pointy

The problem is the way you've got jsfiddle set up. On the left is a pull-down to choose how the site incorporates your JavaScript into the result page. Set it to "no wrap (head)" and it'll work. Well, it won't work, actually, but it'll call your function.

问题是您设置 jsfiddle 的方式。左侧是一个下拉菜单,用于选择站点如何将您的 JavaScript 合并到结果页面中。将其设置为“no wrap (head)”,它会起作用。好吧,实际上它不起作用,但它会调用您的函数。

The next problem you'll have is that your "submit" button will submit the form immediately after your handler runs. To prevent that, you'll need to stop event propagation.

您将遇到的下一个问题是您的“提交”按钮将在您的处理程序运行后立即提交表单。为了防止这种情况,您需要停止事件传播。

回答by ToddBFisher

It looks like your FORM is interfering with your desired results, try this instead:

看起来你的 FORM 正在干扰你想要的结果,试试这个:

<div onclick = "showText()">Click me</div>